【问题标题】:Setting element in nested list using arbitrary length index使用任意长度索引在嵌套列表中设置元素
【发布时间】:2019-04-16 17:44:10
【问题描述】:

我有一些列表和值以任意深度相互嵌套。

nested = [
    3,
    [1, 4, 2],
    [3, [5], 6, 7, [5]],
    [3],
    [[1, 1],[2, 2]]
]

我正在尝试在这个嵌套的混乱中设置一个值 使用任意长的索引。

示例索引:

index = (2, 1)

所以在示例索引处设置一个项目:

nested[2][1] = new_value

如果我们知道索引的长度,我们可以:

nested[index[0]][index[1]] = new_value

问题是索引不是设定的长度!

我想出了如何获取任意长度索引的值:

def nested_get(o, index):
    if not index:
        return o

    return nested_get(o[index[0]], index[1:])

我知道 numpy 数组可以这样做:np_array[index] = new_value

我怎样才能实现一个函数来做类似的事情,但使用纯 python?类似于nested_get,但用于设置值。

【问题讨论】:

  • 设置和获取一样,只需要多传一个参数。当你到达最后一个索引时,做作业。

标签: python python-3.x list nested


【解决方案1】:

你可以用递归函数做一些事情:

def nested_set(x, index, value):
    if isinstance(index, int):
        x[index] = value
        return
    elif len(index) == 1:
        x[index[0]] = value
        return
    nested_set(x[index[0]], index[1:], value)

很可能有一些比列表更好的数据结构来做你想做的事。

【讨论】:

  • @Hadus 可能让您感到困惑的是,您的 getter 使用空数组作为基本情况,但在设置时需要使用 len == 1 作为基本情况,因此您有最后一个要分配的列表到。
  • @user2653663 我什至没有使用列表,而是使用 pytorch 模块 :) 所以它需要对所有使用的模块进行子类化以包含更好的索引,但这已经足够了
  • @Barmar 我没有想到使用索引一个更高的列表来简单地索引它。它只是让我忘记了。
猜你喜欢
  • 2017-03-03
  • 2017-04-18
  • 1970-01-01
  • 2022-10-05
  • 2011-01-25
  • 2013-01-17
  • 1970-01-01
  • 2023-02-04
  • 2020-01-17
相关资源
最近更新 更多