如何解决为什么有时会丢失集合中的“真”值元素?
我在运行以下代码时感到困惑,这是对集合的练习。集合名称“s”中的元素包含布尔值 True。但是,它并不总是被识别或打印。详情请看评论。第二组“s1”的情况并非如此。有人可以尝试告诉我这里出了什么问题。
这是代码:
s = {1,2,32,True,"Trial"}
s1 = { 5,False,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,'Trial'}
s1 is : {False,5}
Union : {32,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 中的 True
是 1
的同义词。所以 True
和 1
具有相同的值,并且一个集合不能包含重复的值。
>>> {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}
如果您尝试创建具有两个值 0
和 False
(结果 {0}
或 {False}
,具体取决于顺序)的集合,您将获得相同的行为表达式)或具有两个值 1
和 1.0
的集合(结果 {1}
或 {1.0}
,取决于表达式的顺序)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。