Python 2.7 嵌套列表的子列表不起作用

Python 2.7 sublist of nested list not working

我在提取子列表时得到了一些奇怪的结果。

list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

交换第一个和第二个索引会产生相同的结果。

list[:][1]
Out[8]: [4, 5, 6]

list[1][:]
Out[9]: [4, 5, 6]

如果我这样做,它会给我一个错误

list[0:1][1]
Traceback (most recent call last):

  File "<ipython-input-10-93d72f916672>", line 1, in <module>
 list[0:1][1]

IndexError: list index out of range

这是 python 2.7 的一些已知错误吗?

当您对列表进行切片时说 0:5,列表将被切片,不包括列表[5]

Ex : l = [0,1,2,3,4,5]
l = l[0:5]
now l is [0,1,2,3,4]

这里的情况相同,所以它在切片之后的列表中唯一存在的第 0 个元素是 [[1,2,3]],这意味着第 0 个元素是 [1,2,3],第 1 个元素超出范围。!

如果您观察 Slice list[0:1],它会创建一个大小为 1 的列表,同样在 Python 中,索引从 0 因此,访问大小为 1 的列表的索引 1 将引发错误 list index out of range

list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  //Original List

list[0:1] // [[1,2,3]]   A list of size 1

list[0:1][1] // This will return list index out of range

list[0:1][0]  // [1,2,3]