【发布时间】:2020-03-28 19:35:26
【问题描述】:
我想遍历列表:
inc_list = ['one', 'two', 'one', 'three', 'two', 'one', 'three']
并创建一个字典,显示相邻单词的所有二元组及其出现次数,同时将倒序组合计数为相等,因此倒序组合并排除相同的单词组合。
所以..'one', 'two'.. 和..'two', 'one'.. 都应该添加到字典中('one', 'two') 的计数中。
预期输出:
{('one', 'two'): 3, ('one', 'three'): 2, ('two', 'three'): 1}
到目前为止,我已经尝试过:
import itertools
from collections import Counter
inc_list = ['one', 'two', 'one', 'three', 'two', 'one', 'three',]
coocurences = dict(Counter(itertools.combinations(inc_list, 2)))
print(coocurences)
这显然计算了所有组合可能性,同时包括反向和相同的单词组合,所以不是我要找的。p>
itertools 中是否有一个工具可以更接近我想要的输出?
我找到了很多关于共现矩阵的信息,但是我更喜欢字典作为输出。
【问题讨论】:
-
您如何区分包含的组合?我的意思是什么时候是 one_two,什么时候是 two_one..
标签: python-3.x dictionary combinations counter find-occurrences