Python slicing of list of list

北慕城南 提交于 2019-12-11 06:57:39

问题


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].


回答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]

Demo:

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



回答2:


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).




回答3:


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]...

You may be confusing somethings that you've seen that utilise numpy which allows extended slicing, eg:

>>> 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:

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



回答4:


s[:] makes a copy of s, so the following [1] accesses the second element of that copy. Which is the same as s[1].

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



回答5:


s[1][:] means a shallow copy of the second item in s, which is [3,4].

s[:][1] means the second item in a shallow copy of s, which is also [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.



来源:https://stackoverflow.com/questions/20306494/python-slicing-of-list-of-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!