为什么集合'True'值元素有时会丢失?



我在运行下面的代码时感到困惑,这是一个关于集合的练习。集合名称"s"中的元素包含布尔值True。但是,它并不总是被识别或打印出来。有关详细信息,请参阅评论。第二个集合"s1"的情况不同。有人能告诉我这里出了什么问题吗。

这是代码:

s = {1,2,32,2,True,"Trial"}
s1 = { 5, False, True, 32}
print("s is : ", s)            # Element True is missing in the output
print("s1 is : ", s1)
print("Union : ",s.union(s1))  # Element True is missing in the output
print("Difference : ",s.difference(s1))
print("Intersection : ", s.intersection(s1)) # Element True is present in the output
print("Elements in s : ",*s)    # Element True is missing in the output of s
print("Elements in s1 : ",*s1)  # Element True is printed in the output of s1
if (True in s ) :
print("True is truely in s")  
else:
print("True not found in s")
if (False in s ) :
print("False is truely in s")
else:
print("Fasle not found in s")
for itm in s :
print(itm, " : ", type(itm)) # Element True is missing in the output
# *** ??? the elemment True in s is printed only in the intersection

我得到的输出是这个

s is :  {32, 1, 2, 'Trial'}
s1 is :  {False, True, 32, 5}
Union :  {32, 1, 2, False, 5, 'Trial'}
Difference :  {2, 'Trial'}
Intersection :  {32, True}
Elements in s :  32 1 2 Trial
Elements in s1 :  False True 32 5
True is truely in s
Fasle not found in s
32  :  <class 'int'>
1  :  <class 'int'>
2  :  <class 'int'>
Trial  :  <class 'str'>
[Done] exited with code=0 in 0.144 seconds

原因是(主要是历史原因(Python中的True1的同义词。因此True1具有相同的值,并且一个集合不能包含重复的值。

>>> {1} == {True}
True
>>> len({1, True})
1
>>> True in {1}
True
>>> 1 in {True}
True

True显示为交集,因为您看到的值1的表示取决于表达式的求值顺序。

>>> s.intersection(s1)
{32, True}
>>> s1.intersection(s)
{32, 1}

如果您尝试创建一个具有两个值0False的集合(结果{0}{False}取决于表达式的顺序(,或者创建一个包含两个值11.0的集合(根据表达式的顺序创建结果{1}{1.0}(,则会得到相同的行为。

最新更新