关于Python计数在每个独特的元素列表

Count of each unique element in a list

本问题已经有最佳答案,请猛点这里访问。

假设我有一个国家列表

1
l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']

然后我有一个独特的国家名单

1
ul = ['India', 'China', 'Japan', 'USA']

我想按升序对列表中每个唯一的国家进行计数。所以输出应该如下:

1
2
3
4
Japan 1
China 2
India 2
USA   2

您可以使用集合中的计数器:

1
2
3
4
5
6
7
8
9
from collections import Counter

l = ["India","China","China","Japan","USA","India","USA"]

new_vals = Counter(l).most_common()
new_vals = new_vals[::-1] #this sorts the list in ascending order

for a, b in new_vals:
    print a, b


如果您不想使用Counter,您可以使用字典计算自己(您已经知道了唯一的元素,因为您有ul):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']

cnts = dict.fromkeys(ul, 0)  # initialize with 0

# count them
for item in l:
    cnts[item] += 1

# print them in ascending order
for name, cnt in sorted(cnts.items(), key=lambda x: x[1]):  # sort by the count in ascending order
    print(name, cnt)  
    # or in case you need the correct formatting (right padding for the name):
    # print('{:<5}'.format(name), cnt)

哪些印刷品:

1
2
3
4
Japan 1
China 2
India 2
USA   2


如果要根据ul列表进行排序,可以使用如下列表理解:

1
2
3
4
5
l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']
result = sorted([(x, l.count(x)) for x in ul], key=lambda y: y[1])
for elem in result:
    print '{} {}'.format(elem[0], elem[1])

输出:

1
2
3
4
Japan 1
India 2
China 2
USA 2

如果您想在按计数排序后按字母排序,可以将result更改为:

1
result = sorted(sorted([(x, l.count(x)) for x in ul]), key=lambda y: y[1])

输出:

1
2
3
4
Japan 1
China 2
India 2
USA 2