【问题标题】:Python2: access nested list using a list of indicesPython2:使用索引列表访问嵌套列表
【发布时间】:2015-05-27 16:33:21
【问题描述】:

如何使用包含索引的另一个列表访问嵌套列表的元素?

例如:

# this is the variable containing the indices
a = [0, 1]

b = [[1,2],[3,4]]

实际上,这些列表中填充了自定义类的元素,并且包含“坐标”(a) 的列表有超过 2 个元素。

是否有可能自动访问 b[0][1] ?以前,我用过这段代码:

c = deepcopy(b)
for el in a:
    c = c[el]

但由于 b 相当大,我很想在不实际操作 b 的情况下摆脱该 deepcopy。

我很高兴有任何建议:)

谢谢!

【问题讨论】:

  • 我感觉到XY Problem
  • 这段代码的目标是什么?
  • 我有一个嵌套列表b,我想使用列表a 中的索引访问它的元素。第二个代码片段只显示了我到目前为止使用的内容。如果你有什么建议,请告诉我:)
  • 真的,正确的做法是b[a[0]][a[1]] 没有漂亮的做法。

标签: python nested-lists


【解决方案1】:

把它扔进一个函数里。这将使其保持范围,因此您不会覆盖原始值

def nested_getitem(container, idxs):
    haystack = container
    for idx in idxs:
        haystack = haystack[idx]
    return haystack

演示:

>>> a = [0, 1]
>>> b = [[1, 2], [3, 4]]
>>> nested_getitem(b, a)
2

如果你疯了,你也可以使用 functools.reduce 来做到这一点。

import functools
import operator

def nested_getitem(container, idxs):
    return functools.reduce(operator.getitem, idxs, container)

【讨论】:

  • 谢谢。这适用于分发元素,但是如果我想操纵该项目怎么办?例如nested_getitem(b,a) = 0.
  • @user3692467 在这种情况下,您为什么要在问题的示例中尝试深度复制???
猜你喜欢
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多