Python issubset在一组集合上

时间:2018-10-21 03:38:20

标签: python set

我有一套:

>>> x = set()
>>> x.add(frozenset({1}))
>>> x.add(frozenset({2}))
>>> x.add(frozenset({3}))
>>> x
{frozenset({2}), frozenset({3}), frozenset({1})}

我有一个候选人集:

>>> y = frozenset({2})
>>> y
frozenset({2})

我想知道我的候选集是否在我的集合中:

>>> y.issubset(x)
False
>>> 

为什么这会返回False?我应该如何确定我的候选集是否在我的集合中?

3 个答案:

答案 0 :(得分:1)

x = set()
x.add(frozenset({1}))
x.add(frozenset({2}))
x.add(frozenset({3}))
print(x)

y = frozenset({2})
print(y in x) # check if candidate set is in set of sets

这应该返回True

答案 1 :(得分:0)

您混淆了子集和元素的概念。

在您的情况下,yx的元素,而不是x的子集。因此,您应该使用y in x(检查y是否是x的元素)而不是y.issubset(x)(检查y的每个元素是否也是...的元素)进行检查x)。

答案 2 :(得分:0)

您的变量略有不同:

  • x := {{1}, {2}, {3}}
  • y := {2}

请注意,x中没有2,因此y并不是x的子集。我想你的意思是:

>>> x = set()
>>> x.add(frozenset({1}))
>>> x.add(frozenset({2}))
>>> x.add(frozenset({3}))
>>> x
{frozenset({2}), frozenset({3}), frozenset({1})}
>>>
>>> {frozenset({2}), frozenset({3}), frozenset({1})}
{frozenset({2}), frozenset({3}), frozenset({1})}
>>>
>>> y = {frozenset({2})}
>>> y.issubset(x)
True
>>>
>>> y = set()
>>> y.add(frozenset({2}))
>>> y.issubset(x)
True
>>> y <= x
True