【问题标题】:How to insert the contents of one list into another如何将一个列表的内容插入另一个列表
【发布时间】:2011-08-13 22:27:37
【问题描述】:

我正在尝试合并两个列表的内容,以便稍后对整个数据集进行处理。我最初查看了内置的insert 函数,但它作为列表插入,而不是列表的内容。

我可以对列表进行切片和附加,但是有没有比这更干净/更 Pythonic 的方式来做我想做的事情:

array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

array = array[:1] + addition + array[1:]

【问题讨论】:

    标签: list python


    【解决方案1】:

    您可以使用赋值左侧的切片语法执行以下操作:

    >>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
    >>> array[1:1] = ['quick', 'brown']
    >>> array
    ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
    

    这几乎是 Python 风格的!

    【讨论】:

      【解决方案2】:

      列表对象的extend 方法执行此操作,但位于原始列表的末尾。

      addition.extend(array)
      

      【讨论】:

      • 虽然大卫的解决方案是 OP 想要的,但你的解决方案是我一直需要的。非常感谢。
      • 我认为添加应该在 .extend() 和它之前的数组中。
      【解决方案3】:

      insert(i,j),其中i 是索引,j 是您要插入的内容,不会添加为列表。相反,它作为列表项添加:

      array = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
      array.insert(1,'brown')
      

      新数组将是:

      array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
      

      【讨论】:

        【解决方案4】:

        利用splat operator / list unpacking 获取您可以使用的列表

        array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
        addition = ['quick', 'brown']
        
        # like this
        array2    = ['the', *addition, 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
        
        # or like this
        array = [ *array[:1], *addition, *array[1:]]
        
        print(array)
        print(array2)
        

        得到

        ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
        

        操作员得到了PEP 448: Additional Unpacking Generalizations的介绍。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-12
          • 1970-01-01
          • 2013-04-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多