用于检查元组是否是一组元组的子集的“issubset”函数

2024-04-18 21:45:24 发布

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

我有一个大小为3的元组和一个大小为2的元组的不同列表。 在Python中,我想检查3大小元组的所有子集是否都存在于元组列表中

Eg:
T3 -> Tuple of size 3: {A, B, C}
Inp -> List of Tuples of Size 2 given as input: [(A,B), (A,C), (B,C), 
       (C,D)]

I want to first get all possible subsets of T3 i.e. (A,B), (A,C), (B,C)
and if all of them are part of Inp then return T3, otherwise do nothing.

到目前为止,我已经能够使用Python itertools.combinations()生成size=2的可能子集

但我还没查到第二部分。你知道吗

我使用了issubset()函数,但它没有返回正确的答案。你知道吗

这是我的密码:

#para gets the tuple T3 or a list of tuples, all of size = n
    def subset_from_kv(para):
        sol = []

        flag = True

        tt = set(para)

        for j in tt:

            for i in set(itertools.combinations(j, n-1)):

                if not(set(i).issubset(inp)): #inp is a list of tuples of size n-1

                    flag = False

            if flag is True:
                sol.append(j)
        return sol

即使所有大小为“n-1”的集合都存在于我的Inp中,函数也返回空列表[]。你知道吗


Tags: of列表sizereturnifall子集flag