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."

输出仅打印列表中的一项。我需要对列表(狗、猫、鸟、狗、狗)进行排序以计算列表中有多少项,例如:

鸟重复1次。cat 重复 1 次。狗重复3次。

问题是它只输出 1 个项目:

鸟重复1次。

4

1 回答 1

1

You need to move your test for z inside the loop:

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."

or, simplified a little:

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

Demo:

>>> 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.

You could also use a collections.Counter() object to do the counting for you, it has a .most_common() method to return results sorted on frequency:

>>> 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.
于 2013-09-16T18:30:55.600 回答