list1 = [1, 2, 3, 4]
element = list1[1:][1]
print(element)为什么它打印3?
这是如何评估的?它是不是先从索引1中获取list1的元素:然后再获取其中的1个索引?
发布于 2018-10-16 04:23:22
Python's grammar指定如何计算它,因为它构造了程序的语法树。
在不深入技术细节的情况下,这样的索引是递归的。这意味着:
foo[bar][qux]简写为:
(foo[bar])[qux]因此,这些指标是从左到右评估的。
它的评估方式如下:
list1 = [1, 2, 3, 4]
temp = list1[1:] # create a sublist starting from the second item (index is 1)
element = temp[1] # obtain the second item of temp (index is 1)(当然,实际上不会创建temp变量,但列表本身是存储在内存中的真实对象,因此也可能更改状态等)。
首先,我们从第二个项目开始进行切片,这会产生一个列表[2, 3, 4],然后我们获得该列表的第二个项目,即3。
https://stackoverflow.com/questions/52824215
复制相似问题