我需要从列表中找到7个最常见的数字。什么是最有效的方法?
这些是列表:
prvo=[20, 9, 1, 19 ,26, 4, 16]
v-ro=[1, 14, 22, 32, 17, 11, 20]
t-to=[32, 3, 31, 29, 15, 12, 20]
c-to=[32, 34, 4, 10, 29, 20, 22]
p-to=[16, 33, 26, 22, 9, 24, 32]
答案 0 :(得分:2)
它有一个内置方法most_common(n)
,给出n个最常用的值
从文档中:
将n个最常见的元素及其计数从最常见到最少的列表返回。如果省略n或None,则most_common()返回计数器中的所有元素。计数相等的元素可以任意排序:
因此成功
from collections import Counter
prvo=[20, 9, 1, 19 ,26, 4, 16]
v_ro=[1, 14, 22, 32, 17, 11, 20]
t_to=[32, 3, 31, 29, 15, 12, 20]
c_to=[32, 34, 4, 10, 29, 20, 22]
p_to=[16, 33, 26, 22, 9, 24, 32]
all_lists = [prvo, v_ro, t_to, c_to, p_to]
counted = []
for li in all_lists:
counted.extend(li)
counter = Counter(counted)
commons = counter.most_common(7)
print([t[0] for t in commons])
您得到:[20, 32, 22, 9, 1, 26, 4]