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

时间:2017-05-17 15:54:59

标签: 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

4 个答案:

答案 0 :(得分:1)

我找到了解决方案:

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  

答案 1 :(得分:0)

你可以用递归来做到这一点:

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)等,那么这也适用于混合嵌套词典/列表。

答案 2 :(得分:-1)

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

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]

答案 3 :(得分:-1)

试试这个来获得o / p:[[1,9],[3,4,9]]

 a = [[1, 2], [3, 4, 5]]
    z=len(a)
    for i in range(0,z):
        a[i][len(a[i])-1]=9
    print (a,len(a[0]))