集合并中`OR, AND`运算符的使用

问题描述 投票:0回答:2

如果问题重复,请耐心等待。但似乎找不到任何相关的问题/解决方案。

假设我有两套:

set_one = {10,5,7}
set_two = {10,1,3,6, 5, 7}
set_one | set_two # union of two sets
{1, 3, 5, 6, 7, 10}
set_one.union(set_two) # same as above
{1, 3, 5, 6, 7, 10}

为什么使用

or
会导致交集而不是并集?检查下面

set_one or set_two # union of two sets
{10, 5, 7} # Shouldn't this be {1, 3, 5, 6, 7, 10}? 

使用

and
会导致并集而不是交集?

set_one & set_two # intersection of two sets
{5, 7, 10}
set_one.intersection(set_two) # same as above
{5, 7, 10}
set.intersection(set_one, set_two) # same as above
{5, 7, 10}

使用

and

set_one and set_two
{1, 3, 5, 6, 7, 10} # Should'n this be {5, 7, 10}

在 python 3.11.5 上运行它

python set
2个回答
1
投票

or
and
是逻辑(布尔)运算符,它们在集合上的操作没有不同。您在这里观察它们的短路行为 - 如果
x or y
在布尔上下文中为 true(任何非空集都是 true),则
x
只是
x
。如果
x and y
为 true,则
y
x


0
投票

事实并非如此。如果您使用的示例中并集和交集碰巧不等于原始两个集合之一,那么

or
and
|
&
之间的区别就更明显了:

>>> set_one = {1, 2, 3}
>>> set_two = {2, 4, 6}
>>> set_one or set_two
{1, 2, 3}
>>> set_one and set_two
{2, 4, 6}
>>> set_one | set_two
{1, 2, 3, 4, 6}
>>> set_one & set_two
{2}

当两个操作数都为真/真时,布尔运算符返回最后一个计算的操作数 - 因此对于

or
来说,它是第一个操作数(如果第一个操作数为真,则不会计算第二个操作数),而对于
and
来说,它是最后一个操作数一个。

|
&
运算符应用于集合时,执行实际的并集和交集运算。

© www.soinside.com 2019 - 2024. All rights reserved.