2013-09-16 79 views
0
my_list=raw_input('Please enter a list of items (seperated by comma): ') 
my_list=my_list.split() 
my_list.sort() 

print "List statistics: " 
print "" 

for x in set(my_list): 
    z=my_list.count(x) 

if z>1: 
    print x, "is repeated", z, "times." 
else: 
    print x, "is repeated", z, "time." 

輸出僅打印列表中的一個項目。我需要對列表(狗,貓,鳥,狗,狗)進行排序以統計列表中有多少物品,例如:Python項目排序

鳥重複1次。貓被重複1次。 狗重複3次。

問題是,它只輸出1項:

鳥被重複1次。

+1

你爲什麼這麼問兩次? [Python列表排序](http://stackoverflow.com/questions/18833681/python-list-sorting) –

+0

你可能想看看collections.Counter對象。 http://docs.python.org/2/library/collections.html#collections.Counter – placeybordeaux

回答

1

您需要將您的測試z循環:

for x in sorted(set(my_list)): 
    z=my_list.count(x) 

    if z>1: 
     print x, "is repeated", z, "times." 
    else: 
     print x, "is repeated", z, "time." 

,或者簡化了一點:

for word in sorted(set(my_list)): 
    count = my_list.count(word) 
    print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '') 

演示:

>>> my_list = ['dog', 'cat', 'bird', 'dog', 'dog'] 
>>> for word in sorted(set(my_list)): 
...  count = my_list.count(word) 
...  print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '') 
... 
bird is repeated 1 time. 
cat is repeated 1 time. 
dog is repeated 3 times. 

你也可以使用collections.Counter() object進行計數你有一個.most_common()方法返回按頻率排序的結果:

>>> from collections import Counter 
>>> for word, count in Counter(my_list).most_common(): 
...  print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '') 
... 
dog is repeated 3 times. 
bird is repeated 1 time. 
cat is repeated 1 time. 
+0

謝謝你的幫助!雖然我仍然有問題。現在不按字母順序排列列表,並且如果它有多個重複的項目(即狗,貓,鳥,狗,狗)打印時:狗重複3次。貓重複一次。鳥重複一次。狗重複3次。狗重複3次。謝謝! – user2784808

+0

先生,那太棒了!非常感謝你的幫助,這真的幫助我更好地理解我在做什麼! – user2784808