您需要將您的測試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.
你爲什麼這麼問兩次? [Python列表排序](http://stackoverflow.com/questions/18833681/python-list-sorting) –
你可能想看看collections.Counter對象。 http://docs.python.org/2/library/collections.html#collections.Counter – placeybordeaux