使用存储在另一个列表中的索引追加到列表 [英] Append to a list using indexes stored in another list
问题描述
符合这个问题 ,我正在寻找一种将元素追加到列表的方法,其中指向应该在列表中追加的索引存储在另一个列表中.
In line with this question, I'm looking for a way to append elements to a list where the index pointing to where in the list it should be appended is stored in another list.
考虑列表:
b = [[[[[0.2], [3]], [[4.5], [78]], [[1.3], [0.23]], [[6.], [9.15]]],
[[[3.1], [44]], [[1.], [66]], [[0.18], [2.3]], [[10], [7.5]]],
[[[3], [4.]], [[12.3], [12]], [[7.8], [3.7]], [[1.2], [2.1]]]]]
以及存储在以下位置的索引:
and the indexes stored in:
c = [0, 0, 0, 1]
我需要使用存储在c
中的索引将元素添加到b
中的该位置.
I need to use the indexes stored in c
to append an element into that location in b
.
这行不通:
b[c[0]][c[1]][c[2]][c[3]].append('new element')
因为b
的形状随我的代码的每次运行而变化,因此c
中的元素数也会变化.这就是为什么我需要一种使用c
将new element
附加到b
的 general 方式的原因.
because the shape of b
changes with every run of my code and thus the number of elements in c
. This is why I need a general way of using c
to append the new element
into b
.
类似的东西:
b[*c].append('new element')
这当然不起作用,但是可以让我知道我要干什么.
which of course doesn't work but gives an idea of what I'm after.
推荐答案
您可以使用 reduce
到逐步进入嵌套列表.
You can use operator.getitem
and reduce
to gradually step into the nested lists.
要将项目插入子列表c[:-1]
中的位置c[-1]
:
To insert the item into sublist c[:-1]
at position c[-1]
:
>>> reduce(operator.getitem, c[:-1], b).insert(c[-1], "new")
或将该项目附加到子列表c
:
Or to append the item to sublist c
:
>>> reduce(operator.getitem, c, b).append("new")
要检索索引为c
的项目:
>>> reduce(operator.getitem, c, b)
'new'
这篇关于使用存储在另一个列表中的索引追加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!