Python slicing of list of list

2019-08-03 16:22发布

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

5条回答
ゆ 、 Hurt°
2楼-- · 2019-08-03 16:58

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]
查看更多
beautiful°
3楼-- · 2019-08-03 17:02

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]
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-08-03 17:09

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]
查看更多
小情绪 Triste *
5楼-- · 2019-08-03 17:12

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.

查看更多
贪生不怕死
6楼-- · 2019-08-03 17:15

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

查看更多
登录 后发表回答