这是我键入的列表:
numbers = [[1,'one'],[2,'two'],[3,'three'],[4,'four'],[6,'six']]
我不明白为什么numbers[-1][-1][-1]
会返回'x'
。
这是因为第一个[-1]
得到列表[[1,'one'],[2,'two],[3,'three'],[4,'four'],[6,'six']]
中的最后一个元素,即[6, 'six']
。
然后,第二个[-1]
获得该列表中的最后一个元素,即six
。
最后,第三个[-1]
返回字符串six
中的最后一个字符,即x
。
方括号([]
(告诉python在索引中获取内容,而-1
是最后一个。字符串可以被认为是字符列表,这就是x
从该字符串返回的原因。
-1索引,表示列表的最后一个元素。你可以看到
e0 = in_nums[-1] # [6, 'six']
e1 = e0[-1] # 'six'
e2 = e1[-1] # 'x'
之所以会发生这种情况,是因为当访问列表或字符串上的-1元素时,实际上是访问该列表(或str(最后一个索引上的项。也就是说,我们有:
numbers[-1] -> [6, 'six'] # returns the last element (a list)
numbers[-1][-1] -> 'six' # returns the last element of the above list
numbers[-1][-1][-1] -> 'x' # returns the last element of the above str