Python 设置类、 float 和整数求值

标签 python class collections set

我还没有看到 set Class 的实现细节,但我想答案就在某处。 Python 赋值基本上评估右值并使用标识符作为引用对象以指向类对象。集合也是如此,即它们是抽象数据结构或引用对象的“集合”。集合不允许重复,当我像这样创建集合时:

s1 = {False, 1.0, 1, "a"} > {False, 1.0, "a"}

Float 类胜过 int 类,显然它们评估的是同一件事。但为什么 float 显示而 init 不显示?我似乎找不到合适的答案或在源代码中看到它。

顺便提一下,我注意到如果使用 .union() 操作,True 和 False 将以某种方式分别取代 1 和 0。所以看起来 Floats 战胜了 Ints,Ints 战胜了 Bools。但是,

>>> s1 = {False, 'a', 1}
>>> s2 = {True, 'a', 0}

>>> s1 | s2
{False, 1, 'a'} 

错误仍然存​​在。我不知道这是否是一个 REPL 问题,但在再次测试之后我每次都得到 {0, 1, 'a'}我不知道发生了什么。

>>> s1 = {True, 'a', 1}
>>> s1
{1, 'a'}
>>> s2 = {False, 'a', 0}
>>> s2
{0, 'a'}

我错过了什么?

>>> s1.union(s2)
{0, 1, 'a'}

最佳答案

来自 https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy :

The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

关于Python 设置类、 float 和整数求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445833/

相关文章:

java - 如何获得无序的键值对

java - 为什么会引发ConcurrentModificationException以及如何对其进行调试

python - 使用网络摄像头 OpenCV 将多条线连接到屏幕中心

python - 检查两个顶点是否在 iGraph 中连接

Python Tkinter 可滚动框架类?

javascript - 在类方法中使用 Puppeteer

java - ClassNotFoundException Sandwich.Java...它在哪里?

Java 加密内存类加载器

python - Python的幂运算符**的一个bug?

c# - 在 C# 中定义 BitVector32 集合时命名空间错误