我试图让这个代码:
from collections import Counter
a = input('Votes: ')
a = a.split(',')
count = Counter(a)
print (count)
当我输入这样的内容时:
One,One,Two,Two,Three,Four,Five,Five
打印出来:
One: 2
Two: 2
Three: 1
Four: 1
Five:2
而不是:
Counter({'One': 2, 'Two': 2, 'Five': 2, 'Three': 1, 'Four': 1})
答案 0 :(得分:1)
for key, c in count.most_common():
print("{}: {}".format(key, c))
most_common()
方法为您提供排序顺序的项目,从最常见到最不常见:
如果您需要先按照他们的顺序订购。在a
中排序{One
之前Two
只是因为先提到One
,然后按照str.index()
的字符串索引对它们进行排序。
for key, c in sorted(count.items(), key=lambda i: a.index(i[0])):
print("{}: {}".format(key, c))
如果您需要通过数字的序数解释来订购它们,请使用将字词翻译成数字的字典:
numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # expand as needed
for key, c in sorted(count.items(), key=lambda i: numbers[i[0].lower()]):
print("{}: {}".format(key, c))
演示:
>>> from collections import Counter
>>> a = 'One,One,Two,Two,Three,Four,Five,Five'.split(',')
>>> count = Counter(a)
>>> for key, c in count.most_common():
... print("{}: {}".format(key, c))
...
Five: 2
Two: 2
One: 2
Three: 1
Four: 1
>>> for key, c in sorted(count.items(), key=lambda i: a.index(i[0])):
... print("{}: {}".format(key, c))
...
One: 2
Two: 2
Three: 1
Four: 1
Five: 2
>>> numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> for key, c in sorted(count.items(), key=lambda i: numbers[i[0].lower()]):
... print("{}: {}".format(key, c))
...
One: 2
Two: 2
Three: 1
Four: 1
Five: 2
答案 1 :(得分:1)
from collections import Counter
a = input('Votes: ')
a = a.split(',')
count = Counter(a)
for key in sorted(set(a),key=lambda x: a.index(x)):
print ("{}: {}".format(key,count[key]))
In [13]: for key in sorted(set(a),key=lambda x: a.index(x)):
....: print ("{}: {}".format(key,count[key]))
....:
One: 2
Two: 2
Three: 1
Four: 1
Five: 2
创建set
以删除重复项,并使用sorted
与lambda
进行排序,以根据a
列表中与{匹配的input
列表中相应值的索引进行排序{1}}订单
答案 2 :(得分:0)
一个班轮,分类:
a = ['One','One','Two','Two','Three','Four','Five','Five']
counts = Counter(a)
print('\n'.join('{}: {}'.format(*x) for x in sorted(counts.items(), key=lambda x: a.index(x[0]))))