'先验建立2个集合中的3个词组'

2024-04-19 02:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做Apriori算法的实现,现在我要创建3组单词

假设我有这样两个单词的列表

FI2 = [('a','b'),('a','c'),('a','d'),('b','d'),('b','e'),('e','f')];

我使用的第一种方法是将所有元素区分为一个单词并使用itertools.组合因为结果应该是C2的子集,所以这是一种计算复杂且不正确的方法

应该是这样的结果

C3 = [('a','b','c'),('a','b','d'),('a','c','d'),('b','d','e')]

我对如何处理这个问题有个问题。我会很感激如何给我一些指导如何做这一个


Tags: 方法算法元素列表单词子集区分指导
1条回答
网友
1楼 · 发布于 2024-04-19 02:30:08

有没有可能C3缺少一些值?('b','e','f'),('a','b','e')

我确信这不是最好的方法,但这是一个开始:

from itertools import combinations 

FI2 = [('a','b'),('a','c'),('a','d'),('b','d'),('b','e'),('e','f')]

# check if two tuples have at least one var in common
check_intersection = (lambda c: len(set(c[0]).intersection(set(c[1]))) > 0)

# run on all FI2 pairs combinations
# if two tuples have at least one var in common, a merged tuple is added
# remove the duplicates tuples from the new list
C3 = list(set([tuple(sorted(set(c[0] + c[1])))for c in combinations(FI2,2) if check_intersection(c)]))



print(C3)
#=> [('b', 'd', 'e'), ('a', 'b', 'e'), ('b', 'e', 'f'), ('a', 'b', 'd'), ('a','c','d'), ('a', 'b', 'c')]

相关问题 更多 >