如何以编程方式在给定索引的嵌套列表中设置元素?

2024-04-19 18:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在给定索引列表的任意嵌套列表中设置一个元素。例如,假设我们有一个列表:

a = [[1, 2], [3, 4, 5]]

我们可以设置如下元素:

a[1][2] = 9

修改后的列表a是:

[[1, 2], [3, 4, 9]]

我想给索引列表设置这个元素:[1, 2]。你知道吗

谢谢!你知道吗

为清晰起见进行编辑:索引列表的长度可能会有所不同。例如,给定索引列表:idx = [1, 2],如建议的那样,我们可以:

a[idx[0]][idx[1]] = 9

然而,在更一般的情况下,idx可以是任何长度。我想要这样的东西:

a[idx[i_1]][idx[i_2]][...][idx[i_n]] = 9

Tags: 元素编辑列表情况建议idx
3条回答

您可以使用递归来实现这一点:

def get_deep(l, indices):
     if (len(indices) > 1) and isinstance(l[indices[0]], list):
         return get_deep(l[indices[0]], indices[1:])
     else:
         return l[indices[0]]

def set_deep(l, indices, value):
     if (len(indices) > 1) and isinstance(l[indices[0]], list):
         set_deep(l[indices[0]], indices[1:], value)
     else:
         l[indices[0]] = value

所以:

In [19]: a = [[1, 2], [3, 4, 5]]

In [20]: get_deep(a, [1, 2])
Out[20]: 5

In [21]: set_deep(a, [1, 2], 9)

In [22]: a
Out[22]: [[1, 2], [3, 4, 9]]

请注意,如果您将中的list类更改为(list, dict),等等,那么这也适用于混合嵌套的dict/list。你知道吗

我找到了解决办法:

def set_in_list(a, idx, val):

    """
        Set an element to value `val` in a nested list `a`. The position
        of the element to set is given by the list `idx`.

        Example:

        `a` = [[1, 2], [3, [4, 5], 6], [7]]
        `idx` = [1,1,0]
        `val` = 9

        ==> `a` = [[1, 2], [3, [9, 5], 6], [7]]

    """

    for i in range(len(idx) - 1):

        a = a[idx[i]]

    a[idx[-1]] = val  

可以使用按元组索引的词典:

my_dict = dict()
my_dict[4, 5] = 3
my_dict[4, 6] = 'foo'
my_dict[2, 7] = [1, 2, 3]


for key in my_dict:
    print(key, my_dict[key])

# (4, 5) 3
# (4, 6) foo
# (2, 7) [1, 2, 3]

相关问题 更多 >