大卫的解决方案是最好的。
但可能更多的乐趣比什么,在这里是不导入任何模块的解决方案:
dicto = {}
for ele in mylist:
try:
dicto[ele] += 1
except KeyError:
dicto[ele] = 1
top_10 = sorted(dicto.iteritems(), key = lambda k: k[1], reverse = True)[:10]
结果:
>>> top_10
[('and', 13), ('all', 2), ('as', 2), ('borogoves', 2), ('boy', 1), ('blade', 1), ('bandersnatch', 1), ('beware', 1), ('bite', 1), ('arms', 1)]
编辑:
回答跟进问题:
new_dicto = {}
for val, key in zip(dicto.itervalues(), dicto.iterkeys()):
try:
new_dicto[val].append(key)
except KeyError:
new_dicto[val] = [key]
alph_sorted = sorted([(key,sorted(val)) for key,val in zip(new_dicto.iterkeys(), new_dicto.itervalues())], reverse = True)
结果:
>>> alph_sorted
[(13, ['and']), (2, ['all', 'as', 'borogoves']), (1, ['"and', '"beware', '`twas', 'arms', 'awhile', 'back', 'bandersnatch', 'beamish', 'beware', 'bird', 'bite', 'blade', 'boy', 'brillig'])]
,一旦出现按字母顺序排序,如果你发现有些话对他们有多余的引号的字。
编辑:
在回答另一个跟进的问题:
top_10 = []
for tup in alph_sorted:
for word in tup[1]:
top_10.append(word)
if len(top_10) == 10:
break
结果:
>>> top_10
['and', 'all', 'as', 'borogoves', '"and', '"beware', '`twas', 'arms', 'awhile', 'back']
接受此消息! – 2012-04-11 04:05:46
就是这样。没有更多的在灌木丛中跳动。 – 2012-04-11 04:22:36
我没有python的最新版本,也无法使用计数器 – 2012-04-11 04:41:45