这些集合运算是什么?为什么它们给出不同的结果?

2024-04-25 04:21:58 发布

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

我在Pluralsight上看到了这个测试题:

鉴于这些情况:

x = {'a', 'b', 'c', 'd'}
y = {'c', 'e', 'f'}
z = {'a', 'g', 'h', 'i'}

x | y ^ z的值是多少

预期的答案是:

{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'}

组合集合(自动丢弃重复项),并从最低到最高排序

我的问题是:

  • 这个表达式叫什么
  • 为什么我从3个不同的Python版本中得到3个不同的结果

Ubuntu 18.04上Python 3.7.5的结果:

{'c', 'h', 'f', 'd', 'b', 'i', 'g', 'a', 'e'}

Ubuntu 18.04上Python 2.17.17rc1的结果:

set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h'])

Windows 10上Python 3.7.2的结果:

{'a', 'd', 'h', 'f', 'b', 'g', 'e', 'c', 'i'}

下面是我用于此目的的相同代码的repl: https://repl.it/repls/RudeMoralWorkplace

我想了解这些表达背后发生了什么,这样我就可以揭穿为什么我会得到不同的结果


Tags: 答案代码https目的版本排序表达式ubuntu
1条回答
网友
1楼 · 发布于 2024-04-25 04:21:58

您提到的集合操作包括:

^-symmetric difference(异或):

Return a new set with elements in either the set or other but not both.

示例:{'1', '2', '3'} ^ {'2', '3', '4'} = {'1', '4'}

|-union(或):

Return a new set with elements from the set and all others.

示例:{'1', '2', '3'} | {'2', '3', '4'} = {'1', '2', '3', '4'}

python中还有其他集合操作:

&-intersection(和):

Return a new set with elements common to the set and all others.

示例:{'1', '2', '3'} & {'2', '3', '4'} = {'2', '3'}

--difference:

Return a new set with elements in the set that are not in the others.

示例:{'1', '2', '3'} - {'2', '3', '4'} = {'1'}

这些操作的优先级顺序为-, &, ^, |,因此在您的示例中,我们首先应用^

>>> y^z
{'a', 'c', 'e', 'f', 'g', 'h', 'i'}

然后|

>>> x|{'a', 'c', 'e', 'f', 'g', 'h', 'i'}
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'}

您描述的不同输出实际上是同一个集合,因为集合没有顺序

>>> {'c', 'h', 'f', 'd', 'b', 'i', 'g', 'a', 'e'} == {'a', 'd', 'h', 'f', 'b', 'g', 'e', 'c', 'i'}
True

集合的字符串表示中显示的任何顺序都是一个实现细节,不应依赖于它,因为它会发生不可预测的变化,正如您所发现的那样

相关问题 更多 >