简体   繁体   English

清单清单的Python切片

[英]Python slicing of list of list

Say I have a list of lists 说我有一个清单清单

    >>> s = [ [1,2], [3,4], [5,6] ]

I can access the items of the second list: 我可以访问第二个列表中的项目:

    >>> s[1][0]
    3
    >>> s[1][1]
    4

And the whole second list as: 整个第二个列表为:

    >>> 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. 我认为这会给我三个列表中每个列表的第二项。

One can use list comprehension to achieve this (as in question 13380993 ), but I'm curious how to properly understand s[:][1] . 可以使用列表理解来实现这一点(如问题13380993所示 ),但是我很好奇如何正确理解s[:][1]

s[:] returns a copy of a list. s[:]返回列表的副本 The next [...] applies to whatever the previous expression returned, and [1] is still the second element of that list. 下一个[...]适用于先前返回的表达式,而[1]仍然是该列表的第二个元素。

If you wanted to have every second item, use a list comprehension: 如果您想拥有第二个项目,请使用列表理解:

[n[1] for n in s]

Demo: 演示:

>>> s = [ [1,2], [3,4], [5,6] ]
>>> [n[1] for n in s]
[2, 4, 6]

The behavior can be understood easily, if we decompose the command: 如果我们分解命令,则行为很容易理解:

s[:]

will return the entire list: 将返回整个列表:

[[1, 2], [3, 4], [5, 6]]

selecting [1] now gives the second list (python indexing starts at zero). 现在选择[1]给出第二个列表(python索引从零开始)。

s[:][1] means take a shallow copy of s and give me the first element from that... While s[1][:] means give me a shallow copy of s[1] ... s[:][1]表示取s的浅表副本,然后从中给我第一个元素...而s[1][:]表示给我s[1]的浅表副本...

You may be confusing somethings that you've seen that utilise numpy which allows extended slicing, eg: 您可能会混淆一些使用numpy进行扩展切片的东西,例如:

>>> a = np.array([ [1,2], [3,4], [5,6] ])
>>> a[:,1]
array([2, 4, 6])

Which with normal lists, as you say, can be done with a list-comp: 正如您所说,使用普通列表可以使用list-comp来完成:

second_elements = [el[1] for el in s]

s[:] makes a copy of s , so the following [1] accesses the second element of that copy. s[:]复制s ,因此以下[1]访问该副本的第二个元素。 Which is the same as s[1] . s[1]相同。

>>> s = [ [1,2], [3,4], [5,6] ]
>>> s[1]
[3, 4]
>>> s[:][1]
[3, 4]

s[1][:] means a shallow copy of the second item in s , which is [3,4] . s[1][:]表示s第二个项目的浅表副本 ,即[3,4]

s[:][1] means the second item in a shallow copy of s , which is also [3,4] . s[:][1]表示s的浅表副本中s第二项,它也是[3,4]

Below is a demonstration: 下面是一个演示:

>>> s = [ [1,2], [3,4], [5,6] ]
>>> # Shallow copy of `s`
>>> s[:]
[[1, 2], [3, 4], [5, 6]]
>>> # Second item in that copy
>>> s[:][1]
[3, 4]
>>> # Second item in `s`
>>> s[1]
[3, 4]
>>> # Shallow copy of that item
>>> s[1][:]
[3, 4]
>>>

Also, [1] returns the second item, not the first, because Python indexes start at 0 . 同样, [1]返回第二项,而不是第一项,因为Python索引从0开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM