2017-04-13 41 views
0

沿所以我有這樣一個字符串列表:數出現在最出現Python列表和返回值與量

mylist = ['foo', 'bar', 'foo', 'bar', 'abc'] 

,我想有一個像這樣的輸出:

foo exists twice 
bar exists twice 
abc exists once 

我已經嘗試將列表轉換爲以字符串作爲鍵的字典,並且值在列表中每次出現都增加。 但我無法按照能夠打印字數最多的字符串的方式對字典進行排序。 我也試過使用2維數組,也沒有工作。有沒有人知道這樣做的好方法?

回答

1

您可以使用dictdefault_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 
相關問題