清单清单的Python切片 [英] Python slicing of list of list
问题描述
说我有一个列表清单
>>> s = [ [1,2], [3,4], [5,6] ]
我可以访问第二个列表中的项目:
I can access the items of the second list:
>>> s[1][0]
3
>>> s[1][1]
4
整个第二个列表为:
>>> s[1][:]
[3, 4]
但是下面的原因为什么也给我第二个列表?
But why does the following give me the second list as well?
>>> s[:][1]
[3, 4]
我认为这会给我三个列表中每一个的第二项.
I thought it would give me the second item from each of the three lists.
一个人可以使用列表理解来实现这一点(如问题13380993 ),但我很好奇如何正确理解s[:][1]
.
One can use list comprehension to achieve this (as in question 13380993), but I'm curious how to properly understand s[:][1]
.
推荐答案
s[:]
返回列表的副本.下一个[...]
适用于先前返回的表达式,而[1]
仍然是该列表的第二个元素.
s[:]
returns a copy of a list. The next [...]
applies to whatever the previous expression returned, and [1]
is still the second element of that list.
如果您想拥有第二个项目,请使用列表理解:
If you wanted to have every second item, use a list comprehension:
[n[1] for n in s]
演示:
>>> s = [ [1,2], [3,4], [5,6] ]
>>> [n[1] for n in s]
[2, 4, 6]
这篇关于清单清单的Python切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!