AH7*_*AH7 4 python list frequency counting
我是python编程的新手,所以请关注我的新手问题......
我有一个初始列表(list1),我已经清理了重复项,最后只有一个列表,每个值只有一个(list2):
list1 = [13,19,13,2,16,6,5,19,20,21,20,13,19,13,16],
list2 = [13,19,2,16,6,5,20,21]
我想要的是计算"list2"中每个值出现在"list1"中的次数,但我无法弄清楚如何做到这一点而不会出错.
我正在寻找的输出类似于:
数字13在list1中表示1次.........数字16在list1中表示2次.
visited = []
for i in list2:
if i not in visited:
print "Number", i, "is presented", list1.count(i), "times in list1"
visited.append(i)
Run Code Online (Sandbox Code Playgroud)
最简单的方法是使用计数器:
from collections import Counter
list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16]
c = Counter(list1)
print(c)
Run Code Online (Sandbox Code Playgroud)
给
Counter({2: 1, 5: 1, 6: 1, 13: 4, 16: 2, 19: 3, 20: 2, 21: 1})
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用与访问dicts相同的语法来访问表示项目及其出现次数的计数器的键值对:
for k, v in c.items():
print('- Element {} has {} occurrences'.format(k, v))
Run Code Online (Sandbox Code Playgroud)
赠送:
- Element 16 has 2 occurrences
- Element 2 has 1 occurrences
- Element 19 has 3 occurrences
- Element 20 has 2 occurrences
- Element 5 has 1 occurrences
- Element 6 has 1 occurrences
- Element 13 has 4 occurrences
- Element 21 has 1 occurrences
Run Code Online (Sandbox Code Playgroud)