检查一组元组是否包含来自另一个

2024-05-23 21:18:11 发布

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

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

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

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

^{pr2}$

但是,如果:

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.

一。在


Tags: 字符串falsetruefooisvarwithnot
3条回答

试试这个:

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)

这不像其他的“紧凑”,但工作原理是一样的。在

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')

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

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的确切工作方式(我不能百分之百地确定文档是什么样子的),并且如果您多次重用foo或{},因此可以预先对其中一个部分进行一次排序。在

相关问题 更多 >