我有一个包含93个不同字符串的列表。我需要找到10个最频繁的字符串,返回必须是从最频繁到最不频繁的顺序。
mylist = ['"and', '"beware', '`twas', 'all', 'all', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'arms', 'as', 'as', 'awhile', 'back', 'bandersnatch', 'beamish', 'beware', 'bird', 'bite', 'blade', 'borogoves', 'borogoves', 'boy', 'brillig']
# this is just a sample of the actual list.我没有最新版本的python,也不能使用计数器。
发布于 2012-04-11 12:04:24
您可以使用collections module中的Counter来执行此操作。
from collections import Counter
c = Counter(mylist)然后执行c.most_common(10)返回
[('and', 13),
('all', 2),
('as', 2),
('borogoves', 2),
('boy', 1),
('blade', 1),
('bandersnatch', 1),
('beware', 1),
('bite', 1),
('arms', 1)]发布于 2012-04-11 12:54:28
David的回答是最好的-但如果您使用的Python版本不包括集合模块(在Python2.7中引入)中的计数器,则可以使用执行相同操作的Counter类的this implementation。我怀疑它会比模块慢,但会做同样的事情。
发布于 2012-04-11 13:10:30
David的解决方案是最好的。
但可能更多的是为了好玩,这里有一个不导入任何模块的解决方案:
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']https://stackoverflow.com/questions/10099602
复制相似问题