Python清单-正确/错误的前两个元素? [英] Python list - True/False first two elements?
问题描述
发布此问题后,经历了一些试验和错误,我观察到以下现象:
Following some trial and error after posting this question, I observe the following phenomena:
>>> [1,2][True]
2
>>>>[1,2][False]
1
>>>>[1,2,3][True]
2
如果我添加第三个或后续元素,则无效.
If I add a third or subsequent element, it has no effect.
有人可以指出我对这些观察结果的解释吗?我想这是一些与任何Python列表中的前两个元素有关的常规属性吗?
Can someone point me to the an explanation of these observations? I presume this is some general property relating to the first two elements in any Python list?
谢谢
推荐答案
由于 [1,2,3] [True]
有两组[]
的解释方式不同.
What's happening here is a little confusing, since [1,2,3][True]
has two sets of []
s that are being interpreted in different ways.
如果我们将代码分成几行,那么发生的事情会更加清楚.
What's going on is a little more clear if we split the code over a few lines.
第一组 []
构造一个列表对象.让我们为该对象分配名称 a
:
The first set of []
s construct a list object. Let's assign that object the name a
:
>>> [1,2,3]
[1, 2, 3]
>>> a = [1,2,3]
>>>
第二组 []
指定该列表内的索引.您通常会看到这样的代码:
The second set of []
specify an index inside that list. You'd usually see code like this:
>>> a[0]
1
>>> a[1]
2
>>>
但是直接使用列表对象而不用给它起一个名字同样有效:
But it's just as valid to use the list object directly, without ever giving it a name:
>>> [1,2,3][0]
1
>>> [1,2,3][1]
2
最后, True
和 False
可用作索引的事实是因为它们被视为整数.来自数据模型文档:>
Lastly, the fact that True
and False
are useable as indexes is because they're treated as integers. From the data model docs:
共有三种类型的整数:
There are three types of integers:
普通整数....
长整数.....
布尔值
这些代表真值False和True.他们俩代表值False和True的对象是唯一的布尔值对象.布尔类型是纯整数的子类型,布尔类型几乎在所有值中,值的行为分别类似于值0和1上下文,例外情况是当转换为字符串时,分别返回字符串"False"或"True".
These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, 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.
因此, [1,2,3] [True]
等效于 [1,2,3] [1]
这篇关于Python清单-正确/错误的前两个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!