如何获取包含元组的两个或多个列表的交集?

2024-03-29 12:08:29 发布

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

我想比较两个或更多列表中的元组,并打印出它们的交集。我在每个元组中有25个元素(包括空元素),每个列表中的元组计数都会发生变化。你知道吗

到目前为止,我尝试了两个列表的交集,我使用的代码如下所示:

res_final = set(tuple(x) for x in res).intersection(set(tuple(x) for x in res1))

output:

set()

(res和res1是我的列表)


Tags: 代码in元素列表foroutputresfinal
2条回答

希望这个例子有帮助:

import numpy as np
np.random.seed(0)  # random seed for repeatability
a_ = np.random.randint(15,size=(1000,2))  # create random data for tuples
b_ = np.random.randint(15,size=(1000,2))  # create random data for tuples
a, b = set(tuple(d) for d in a_), set(tuple(d) for d in b_)  # set of tuples
intersection = a&b  # intersection
print(intersection)  # result

在代码中,创建随机变量矩阵,然后将行转换为元组。然后我们得到元组的集合,最后是对你来说最重要的部分,元组的交集。你知道吗

如果您的输入如下所示:

in_1 = [(1, 1), (2, 2), (3, 3)]
in_2 = [(4, 4), (5, 5), (1, 1)]
in_3 = [(6, 6), (7, 7), (1, 1)]
ins = [in_1, in_2, in_3]

然后我想你可以用itertools.combinations来找到两两相交的地方,然后从中取一个set来删除重复的地方。你知道吗

from itertools import combinations

intersected = []
for first, second in combinations(ins, 2):
    elems = set(first).intersection(set(second))
    intersected.extend(elems)

dedup_intersected = set(intersected)
print(dedup_intersected)
# {(1, 1)}

相关问题 更多 >