Slicing element from sublist - Python

我的梦境 提交于 2019-12-01 13:34:29

问题


I want to return the number 5 from this:

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

I thought this would work but it is not:

print(list_1[1:1])

It returns an empty list. It is Index 1 (second list) and position 1 (second number in the list).

Shouldn't that work?


回答1:


You need two separate operations:

sub_list = list_1[1]
item = sub_list[1]
# or shortly list_1[1][1]

What you did was calling the slice interface which has an interface of [from:to:step]. So it meant: "give me all the items from index 1 to index 1" (read about slicing for more information).




回答2:


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

then

list_1[0] == [1,2,3]
list_1[1] == [4,5,6]

then

list_1[1][1:1] == []  #slice starting from position '1', and around to the position before '1', effectively returning an empty list
list_1[1][1] == 5

edit corrections as from comments




回答3:


list_1[1][1]

The first [1] gives you [4, 5, 6]. The next [1] gives you 5




回答4:


Let's say we have a list:

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

You're question asks, why does

list_1[1:1]

Return []?

Because you're asking for the objects from index 1 to index 1, which is nothing.

Take a simple list:

>>> x = [1, 2, 3]
>>> x[1:1]
[]

This is also empty because you're asking for all objects from index 1 to index 1.

All the 2nd number does is say the maximum reach non-inclusive. So...

>>> x = [1, 2, 3]
>>> x[1:10000]
[2, 3]
>>> x[1:-1023]
[]
>>> x[1:2]
[2]

If the 1st number is equal to or greater than the 2nd number, you'll always end up with an empty list unless you change the step of the slice (if it's equal, it'll always be empty)

Of a 2-dimensional array, if you wanted the 2nd object of the 2nd list in the list:

>>> list_1[1]
[4, 5, 6]
>>> list_1[1][1]
5


来源:https://stackoverflow.com/questions/49183851/slicing-element-from-sublist-python

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