检查一组元组是否包含另一组中的项目

时间:2016-11-17 23:16:02

标签: python python-3.x set tuples

假设我有一组像这样的元组:

foo = {('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')}
var = {'A', 'C', 'B'}

我想检查var中的每个项是否都在元组集中的任何位置,如果是,则返回True,如果不是则返回False。 我试过这个,但到目前为止我没有运气。

all((x for x in var) in (a,b) for (a,b) in foo)
Desired output : True
Actual output : False

但是如果:

var = {'A','C','D'} 

我希望它返回False,逻辑是检查字符串是否“彼此知道”。

好的,让我们解释一下,我的上一篇文章。

A is paired with C, C is paired D, however D is not paired with A.

对于我的第一个逻辑,

A is paired with B,B is paired with C,C is paired with B, C is paired with A, Everyone 'knows' each other.

3 个答案:

答案 0 :(得分:2)

生成您希望出现的所有对,并通过子集检查查看它们是否存在:

from itertools import combinations

def _norm(it):
    return {tuple(sorted(t)) for t in it}

def set_contains(foo, var):
    return _norm(combinations(var, 2)) <= _norm(foo)

print(set_contains({('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')},
                   {'A', 'C', 'B'}))  # True

print(set_contains({('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')},
                   {'A', 'C', 'D'}))  # False

有可能减少排序量,具体取决于combinations的确切运作方式(我不能100%确定如何制作文档)以及是否重复使用{{1或多次foo,因此可以事先对其中一个部分进行排序。

答案 1 :(得分:0)

试试这个:

foo = {('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')}
var = {'A', 'C', 'B'}

for elem in var:
    if any(elem in tuples for tuples in foo):
        print(True)

答案 2 :(得分:0)

这不像其他人那样“紧凑”,但效果相同。

for x in var:
    for y in foo:
        if x in y:
            print('Found %s in %s' % (x, y))
        else:
            print('%s not in %s' % (x, y))

B not in ('C', 'D')
B not in ('A', 'C')
Found B in ('A', 'B')
Found B in ('B', 'C')
A not in ('C', 'D')
Found A in ('A', 'C')
Found A in ('A', 'B')
A not in ('B', 'C')
Found C in ('C', 'D')
Found C in ('A', 'C')
C not in ('A', 'B')
Found C in ('B', 'C')
相关问题