【问题标题】:Checking if a set of tuple contains items from another set检查一组元组是否包含另一组中的项目
【发布时间】:2016-11-17 23:16:01
【问题描述】:

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

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.

.

【问题讨论】:

  • 那么你到底想要什么?你想检查 var 中的每个元素是否存在于 foo 中的某个地方吗?或者如果只有 1 个呢?
  • @mrdomoboto 我已编辑,现在检查。
  • 是的,我已经删除了我的答案,因为现在我不知道你在说什么。
  • 你的意思是foo中每个元组的all元素是否都在var中???
  • 好了,我现在解释一下。

标签: python python-3.x set tuples


【解决方案1】:

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

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% 确定文档的内容)以及是否重复使用 foovar多次,因此可以预先对其中一个部分进行一次排序。

【讨论】:

  • 这比我的方法好。
  • 虽然,我可以建议使用set(itertools.chain(*foo)) 而不是set(sum(foo...
  • 几乎是我想要的,但是,如果我想检查 {'A','C','D'} 它应该是 False,我应该在我的帖子中提到,对不起。它检查它们的字符串是否“相关”。
  • @Alex Hall 我尽量解释我的逻辑。
  • 你能在其他函数中实现_norm吗?
【解决方案2】:

试试这个:

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)

【讨论】:

  • 函数需要返回True或False,不能多次打印True 0。
【解决方案3】:

这不像其他的那样“紧凑”,但工作方式相同。

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

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2015-10-28
    • 2019-05-05
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多