How come I can add the boolean value False but not True in a set in Python?(为什么我可以在 Python 的集合中添加布尔值 False 而不是 True?)
问题描述
我刚开始研究 Python 中的 set 数据类型.出于某种原因,每当我将 True 的布尔值添加到集合中时,它都不会出现.但是,如果我将 False 添加到集合中,它将成为集合的元素.当我用谷歌搜索这个问题时,我感到很震惊.
I just started investigating the set data type in Python. For some reason, whenever I add the Boolean value of True to a set it doesn't appear. However, if I add False to a set it will become an element of the set. I was shocked when I googled this question that nothing came up.
example1 = {1, 2, 7, False}
example2 = {7, 2, 4, 1, True}
print(example1)
print(example2)
输出是:
{False, 1, 2, 7}
{1, 2, 4, 7}
推荐答案
因为在 Python 中 1 == True
(和 hash(1) == hash(True)
) 并且您的集合中已经有 1 个.
Because in Python 1 == True
(and hash(1) == hash(True)
) and you have 1 in your set already.
想象一下这个例子:
example1 = {0, False, None}
example2 = {1, True}
print(example1)
print(example2)
将输出:
{0, None}
{1}
第一组有 0
和 None
因为 0 == False
但 0 != None
.使用第二个集合 1 == True
所以 True
不会添加到集合中.
First set has 0
and None
because 0 == False
but 0 != None
. With second set 1 == True
so True
isn't added to the set.
这篇关于为什么我可以在 Python 的集合中添加布尔值 False 而不是 True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我可以在 Python 的集合中添加布尔值 False 而不是 True?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01