【问题标题】:Append to a list using indexes stored in another list使用存储在另一个列表中的索引附加到列表
【发布时间】:2015-03-27 12:26:11
【问题描述】:

根据this question,我正在寻找一种将元素附加到列表的方法,其中指向列表中应附加位置的索引存储在另一个列表中。

考虑一下列表:

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]]]]]

以及存储在的索引:

c = [0, 0, 0, 1]

我需要使用存储在c 中的索引将元素附加到b 中的该位置。

这行不通:

b[c[0]][c[1]][c[2]][c[3]].append('new element')

因为b 的形状会随着我的代码的每次运行而变化,因此c 中的元素数量也会发生变化。这就是为什么我需要使用cnew element 附加到b通用 方式。

类似:

b[*c].append('new element')

这当然行不通,但让我知道我在追求什么。

【问题讨论】:

  • c的最后一个位置不应该是插入元素到列表中的位置,而不是追加?
  • @tobias_k 是的,感谢您引起我的注意。我现在就修。

标签: python list


【解决方案1】:

您可以使用operator.getitemreduce 逐步进入嵌套列表。

要将项目插入到子列表c[:-1] 的位置c[-1]

>>> reduce(operator.getitem, c[:-1], b).insert(c[-1], "new")

或将项目附加到子列表c

>>> reduce(operator.getitem, c, b).append("new")

检索索引c处的项目:

>>> reduce(operator.getitem, c, b)
'new'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多