【问题标题】:How to insert multiple values by index into list at one time如何通过索引一次将多个值插入列表
【发布时间】:2016-05-23 05:16:08
【问题描述】:

我想知道是否有一种方法可以使用相同的索引一次将多个变量插入到列表中。例如,假设我们有一个列表

[a, b, c]

[0,1,2,3,4]

我想插入第一个列表,最终结果是,

[a, 0, 1, b, 2, 3, c, 4]

但是,如果我打算使用 list.insert(pos, value) 单独执行此操作并使用 [0, 2, 4] 的位置,那么使用的后续位置将变得无效,因为它与旧的 5 个元素列表而不是现在的 6 个元素有关。

有什么建议吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
    list_a = [0,1,2,3,4]
    list_b = ["a", "b", "c"]
    pos    = [0, 2, 4]
    
    assert(len(list_b) == len(pos))
    acc = 0
    for i in range(len(list_b)):
        list_a.insert(pos[i]+acc, list_b[i])
        acc += 1
    
    print(list_a)
    

    ['a', 0, 1, 'b', 2, 3, 'c', 4]

    【讨论】:

    • 这非常有效。就像提醒其他人,它只有在位置及其各自元素的顺序正确时才有效,所以如果你有位置 [3, 0, 2, 4],例如,它将不起作用。
    • @Loc-Tran 添加了assert 语句。
    【解决方案2】:

    一个简单的选择是从最高值的位置开始添加项目,然后从第二高的位置继续,等等。

    这样你就可以使用原来的方法,没有任何“旧/新位置”的问题

    【讨论】:

    • 简单,我喜欢。我正要创建一个完整的位置索引,但这是这里最好的解决方案。
    【解决方案3】:

    一种不使用列表推导式的方法:

    >>> a = [0,1,2,3,4]
    >>> b = ['a', 'b', 'c']
    >>> ind = [0, 2, 4]
    >>> d = dict(zip(ind, b))
    
    >>> [t for k in [(d.get(i),j) for i,j in enumerate(a)] for t in k if t is not None]
    ['a', 0, 1, 'b', 2, 3, 'c', 4]
    

    【讨论】:

      【解决方案4】:

      另一种选择,不使用索引累加器,但仍要求索引按升序排列。

      newObjects = ["a", "b", "c"]
      newObjectIndices = [0, 2, 4]
      existingList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      
      for index, obj in zip(reversed(newObjectIndices), reversed(newObjects)):
          existingList.insert(index, obj)
      
      print(existingList)       # ['a', 0, 1, 'b', 2, 3, 'c', 4, 5, 6, 7, 8, 9]
      

      如果不能保证升序,那么排序是一种可能的解决方案。

      newObjects = ["b", "a", "c"]
      newObjectIndices = [2, 0, 4]
      existingList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      
      for index, obj in reversed(sorted( zip(newObjectIndices, newObjects), key=lambda tup: tup[0])):
          existingList.insert(index, obj)
      
      print(existingList)     # ['a', 0, 1, 'b', 2, 3, 'c', 4, 5, 6, 7, 8, 9]
      

      【讨论】:

        猜你喜欢
        • 2022-01-12
        • 2020-05-04
        • 2014-01-15
        • 2019-07-11
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 2019-05-04
        相关资源
        最近更新 更多