python - 使用任意长度索引设置嵌套列表中的元素

标签 python python-3.x list nested

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

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 但用于设置值。

最佳答案

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

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)

很可能有一些比列表更好的数据结构可以满足您的需求。

关于python - 使用任意长度索引设置嵌套列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713873/

相关文章:

python - 如何在Python中打印字符串中带有字母的值的索引?

list - 什么是 Haskell 的 Stream Fusion

python - sqlalchemy - 加入 association_table

python - 如何从 Python3 中给定的值列表中获取字符串中每个字符的值?

python - 我可以通过提供项目名称来引用 Django 模板中的项目 URL 吗?

python - 如何使用 PySerial 将整数写入端口

python - 断言错误 : yield from wasn't used with future

ios - 创建自定义对象列表 F#

python - html按钮使用bottle调用python函数

python - 高效切片三角稀疏矩阵