繁体   English   中英

Python:从列表列表中检索项目

[英]Python: retrieve an item from a list of lists of lists

我有一个列表列表,我想知道从底层列表中检索特定项目的正确方法。

例如,说我要打印100:

tree1 = [[0, 0, 0], [1, 1, 1], [2, 100, 2]]
tree2 = [[[0, 0 ,0], [1, 1, 1], [2, 100, 2]], [[3, 3, 3], [4, 4, 4], [5, 5, 5]]]

print(tree1[3][2])
print(tree2[1][3][2])

第一个示例有效,但第二个示例无效。 Python如何处理“高维”嵌套列表的索引?

实际上,这些都不起作用。 在Python中,列表的索引从0开始。这意味着要在tree1和tree2中打印100,您需要运行:

print(tree1[2][1])
print(tree2[0][2][1])

Python索引从0开始,因此例如:

>>> a=[1,2,3]
>>> a[0]
1
>>> a[1]
2
>>> a[2]
3

因此,您的代码可能是:

print(tree1[2][1])
print(tree2[0][2][1])

“查看”列表索引的一种方法是遍历列表枚举项, 枚举返回元素和索引。

因此,例如:

for index, element in enumerate(tree1):
  print (index, element)

# (0, [0, 0, 0])
# (1, [1, 1, 1])
# (2, [2, 100, 2])

在哪里可以看到索引从0开始。当您调用print(tree1[1]) ,您将获得#=> [1, 1, 1] print(tree1[1]) #=> [1, 1, 1]

为了更深入地了解列表,您可以迭代嵌套元素,例如(我更改了变量的名称):

for i_row, row in enumerate(tree1):
  for i_col, cell in enumerate(row):
    print(i_row, i_col, cell)

返回:

# (0, 0, 0)
# (0, 1, 0)
# (0, 2, 0)
# (1, 0, 1)
# (1, 1, 1)
# (1, 2, 1)
# (2, 0, 2)
# (2, 1, 100)
# (2, 2, 2)

因此,例如调用print(tree1[2][1]) ,返回#=> 100

tree2相同,您可以在其中进一步挖掘一级。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM