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

时间:2017-09-07 18:55:46

标签: python-2.7 nested-lists sublist

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

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的一些已知错误吗?

2 个答案:

答案 0 :(得分:1)

当您将列表切成0:5时,列表将被排除,不包括列表[5]

$?var_name

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

答案 1 :(得分:0)

如果你观察到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]