不同列表中两个项目的Python共现

标签 python list dictionary count find-occurrences

我有一个列表列表,例如:

names =  [['cat', 'fish'], ['cat'], ['fish', 'dog', 'cat'],
 ['cat', 'bird', 'fish'], ['fish', 'bird']]

我想计算每对名字在整个列表中一起提到的次数,输出如下:

{ ['cat', 'fish']: 3, ['cat', 'dog']: 1,['cat','bird']:1
 ['fish','dog'] : 1, ['fish','bird']:2} 

我试过了:

from collections import Counter
from collections import defaultdict

co_occurences = defaultdict(Counter)
for tags in names:
    for key in tags:
        co_occurences[key].update(tags)

print co_occurences

但它不计算主列表中的 co=occurrences。

最佳答案

您可以通过使用 itertools.combinationsitertools.chain 来使用所需的结果:

>>> from itertools import combinations, chain

>>> names =  [['cat', 'fish'], ['cat'], ['fish', 'dog', 'cat'],
...  ['cat', 'bird', 'fish'], ['fish', 'bird']]
>>> uniques = set(chain(*names))
>>> {x: sum(1 for n in names if all(i in n for i in x))  for x in combinations(uniques, 2)}
{('fish', 'dog'): 1, ('dog', 'cat'): 1, ('bird', 'fish'): 2, ('fish', 'cat'): 3, ('bird', 'dog'): 0, ('bird', 'cat'): 1}

关于不同列表中两个项目的Python共现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42272311/

相关文章:

python - 谁能帮我找出这段代码有什么问题吗?相同RNA序列匹配程序

java - List、ArrayList 和 LinkedList 有问题吗?

r - 将列表的多个元素转换为矩阵 R

python - 从 python 中的现有列创建新列

java - 为 map 中的每个元素流口水

c# - 静态通用类作为字典

java - 切换到 Map/Enum 或其他

python - 如何使用 pandas 包为 python 制作的子图清除 boxplot 的默认字幕

python - 使用Paramiko时如何关闭本地回声?

python - 多处理模块和pyro的比较?