Python列表排序 [英] Python List Sorting
本文介绍了Python列表排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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."
我正在尝试使该程序按字母顺序对列表进行排序,然后打印找到的每个列表的数量.输出为:
I am trying to get the program to sort the list alphabetically, then print how many of each it found. The output is:
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.
我只需要打印一次即可.另外,我试图弄清楚如何将项目放在引号中.
I only need it to print one time each. Also, I am trying to figure out how to put the item in quotation marks.
推荐答案
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您可以创建自己的计数器方法
if you are using python < 2.7 you can make your own counter method
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
这篇关于Python列表排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文