数出现在最出现Python列表和返回值与量
问题描述:
沿所以我有这样一个字符串列表:数出现在最出现Python列表和返回值与量
mylist = ['foo', 'bar', 'foo', 'bar', 'abc']
,我想有一个像这样的输出:
foo exists twice
bar exists twice
abc exists once
我已经尝试将列表转换为以字符串作为键的字典,并且值在列表中每次出现都增加。 但我无法按照能够打印字数最多的字符串的方式对字典进行排序。 我也试过使用2维数组,也没有工作。有没有人知道这样做的好方法?
答
您可以使用dict
或default_dict
并按值排序,但不需要重新发明轮子。您需要一个Counter
:
from collections import Counter
counter = Counter(['foo', 'bar', 'foo', 'bar', 'abc'])
print(counter.most_common())
# [('foo', 2), ('bar', 2), ('abc', 1)]
for (word, occurences) in counter.most_common():
print("%s appears %d times" % (word, occurences))
# foo appears 2 times
# bar appears 2 times
# abc appears 1 times