python - 计算一个元素在多个列表中的出现次数

标签 python list python-2.7 python-3.x

我有几个列表:

l1 = [1,2,3,4,5,6,7,8]
l2 = [1,3,5,7]
l3 = [4,5,1,8,2]
l4 = [1,2,6,7]
l5 = [5,7,8]

我想计算每个元素出现的次数,所以输出应该是

element 1 appears in 3 lists
element 2 in 3
element 3 in 2
element 4 in 2
element 5 in 4
...

我可以使用任何内置函数或聪明的想法来做到这一点吗?因为我可以使用循环来做到这一点,但这似乎是一个非常具有破坏性的想法。

最佳答案

我会合并 collections.Counteritertools.chain :

>>> all_lists = [l1, l2, l3, l4, l5]
>>> from itertools import chain
>>> from collections import Counter
>>> all_counts = Counter(chain.from_iterable(all_lists))
>>> for k, v in all_counts.items():
...     print('element', k, 'appears in', v, 'lists')
...     
element 1 appears in 4 lists
element 2 appears in 3 lists
element 3 appears in 2 lists
element 4 appears in 2 lists
element 5 appears in 4 lists
element 6 appears in 2 lists
element 7 appears in 4 lists
element 8 appears in 3 lists

(如果你想保证输出顺序是升序的,你可能想在其中加入一个sorted。)

如果@jonrsharpe 是正确的,并且您需要处理一个元素可以在单个列表中多次出现的情况(现在它真的是“元素 1 出现 4 ”,而不是 4列表),你可以在那里扔一个 set:

all_counts = Counter(chain.from_iterable(map(set, all_lists)))

这样无论一个元素在列表中出现多少次,它都只计为 1。

关于python - 计算一个元素在多个列表中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296358/

相关文章:

减少 R 中的列表以匹配另一个列表。

list - Haskell - 如何创建矩阵

python-2.7 - 如何在 Ubuntu 16.04 上为 Python 2.7 安装 openCV 2.4.13?

python - smart_unicode 在我的 Django 项目中不起作用

python - Python中传统线程和asyncio线程如何通信?

Python 子进程返回错误的退出代码

Python:Azure 存储表无法插入批处理项(当它们存在时)

list - 从Map中获取Scala中给定键列表的值

linux - 比较两个文件并打印不匹配的行

python - 如何在 DJANGO 中按最大相同记录数排序