如何找到 B 中包含 A 的任何元素的所有元素,其中 A 和 B 是不同长度的组合列表?

How to find all elements in B that contain any element of A, where A and B are lists of combinations of different lengths?

假设 A = [[0, 1], [1, 2]],它存储来自 {0, 1, 2, 3} 的两个 2 组合,以及 B = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]],它存储来自 {0, 1, 2, 3} 的所有可能的 3 组合。

如何找到 B 中至少包含来自 A 的 2 个组合之一的所有元素?

我想要的输出是 C = [[0, 1, 2], [0, 1, 3], [1, 2, 3]],其中 [0, 1, 2] 包括 [0, 1][1, 2][0, 1, 3] 包括 [0, 1][1, 2, 3] 包括 [1, 2].

谢谢! (如果答案代码高效且快速,那就太好了,因为我需要为大规模的AB这样做)

我尝试了以下代码:

import numpy as np
import itertools

A = [[0, 1], [1, 2]]
B = []
Cdup = []
rows = range(4)
for combo in itertools.combinations(rows, 3):
    B.append(list(combo))

print(B)

for b in B:
    for a in A:
        if a.issubset(b):
            Cdup.append(b)

C = np.unique(Cdup)

但是有一个错误说 list object has no attribute issubset.

希望这段代码可以成为您场景的解决方案,如果您认为它需要任何解释,请告诉我:

listA=[[0,1],[1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3],[1,2,3]]
res = []

for comA in listA:

    strA = " ".join(str(e) for e in comA)

    for comB in listB:
    
        strB = " ".join(str(el) for el in comB)
    
        if strA in strB:
        
            res.append(list(comB))
            # use tuple if you want to remove duplicates easily:
            # res.append(tuple(comB))


print(res)

# if the res list contain tuples the to remove duplicates we can use:
# mylist = list(dict.fromkeys(res))
# print(mylist)

这是一个使用 itertools.combinations、理解和 set 的解决方案:

from itertools import combinations

A = [(0, 1), (1, 2)]
B = list(combinations(range(4), 3))
C = set(b for a in A for b in B if a in set(combinations(b, len(a))))

print(C)

这导致:

{(0, 1, 2), (0, 1, 3), (1, 2, 3)}

上面的解决方案假定 len(a) <= len(b) 其中 ab 分别是 AB 的元素。它所做的只是检查 A 的每个元素是否是 B 的每个元素的组合的元素,由 A 的元素的 len() 组合而成。

您可以扫描 listB 的每个元素 b 并检查 listA 的任何元素 a 是否是 b 的子集,在这种情况下保持 b.

编码:

[b for b in listB if any(set(a).issubset(set(b)) for a in listA)]