列表中每个唯一元素的计数

时间:2017-06-07 17:11:49

标签: python count

说我有一个国家/地区列表

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

然后我有一个独特的国家/地区列表

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

我希望按升序排列列表中的每个唯一国家/地区。所以输出应该如下:

Japan 1
China 2
India 2
USA   2

3 个答案:

答案 0 :(得分:4)

您可以使用收藏中的计数器:

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

答案 1 :(得分:2)

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

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)  

打印:

Japan 1
China 2
India 2
USA   2

答案 2 :(得分:1)

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

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])

输出:

Japan 1
India 2
China 2
USA 2

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

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

输出:

Japan 1
China 2
India 2
USA 2