2
my_list=raw_input('Please enter a list of items (separated by comma): ')
my_list=my_list.split()
my_list.sort()

print "List statistics: "

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

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

我试图让程序按字母顺序对列表进行排序,然后打印它找到的每个列表的数量。输出是:

List statistics: 
bird, is repeated 1 time.
cat, is repeated 1 time.
dog is repeated 1 time.
dog, is repeated 2 times.
dog, is repeated 2 times.

我只需要它每次打印一次。另外,我想弄清楚如何将项目放在引号中。

4

3 回答 3

3
from itertools import Counter
my_list=raw_input('Please enter a list of items (separated by comma): ')
my_list=my_list.split(",")


print "List statistics: "
import operator
for item,count in sorted(Counter(my_list).items(),key =operator.itemgetter(0)) :

    if z==1:  
        print  '"%s" is repeated %d time.'%(item,count)
    else:
        print  '"%s" is repeated %d times.'%(item,count)

如果您使用的是 python < 2.7,您可以制作自己的计数器方法

def Counter(a_list):
    d = {}
    for item in a_list:
        if d.get(item,None) is None:
           d[item] = 0
        d[item] += 1
    return d
于 2013-09-16T17:18:02.180 回答
1

您可以遍历从列表创建的集合:

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

这样,您只会在循环中获取每个元素一次。

于 2013-09-16T17:15:26.360 回答
0

替换for x in my_list:for x in sorted(list(set(my_list))):

虽然没有在问题中提出,但您可以使用它:

print x, "is repeated", z, "time%s." %("s" if z > 1 else "")

代替:

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

他们称之为“Pythonic”。

于 2013-09-16T17:16:11.833 回答