Python项目排序

时间:2013-09-16 18:29:02

标签: python list sorting

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

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

鸟重复了一次。 猫重复了一次。 狗重复3次。

问题是它只输出1项:

鸟重复了一次。

1 个答案:

答案 0 :(得分: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.