【问题标题】:How to append all elements of one list to another one? [duplicate]如何将一个列表的所有元素附加到另一个列表? [复制]
【发布时间】:2018-01-11 00:46:29
【问题描述】:

可能是一个简单的问题,但我想将一个列表的元素分别解析到另一个列表。例如:

a=[5, 'str1'] 
b=[8, 'str2', a] 

目前

b=[8, 'str2', [5, 'str1']] 

不过我想成为b=[8, 'str2', 5, 'str1']

并且做b=[8, 'str2', *a] 也不起作用。

【问题讨论】:

    标签: python python-2.7 list


    【解决方案1】:

    使用extend()

    b.extend(a)
    [8, 'str2', 5, 'str1']
    

    【讨论】:

      【解决方案2】:

      您可以使用切片在任意位置将一个列表解包到另一个列表中:

      >>> a=[5, 'str1'] 
      >>> b=[8, 'str2'] 
      >>> b[2:2] = a   # inserts and unpacks `a` at position 2 (the end of b)
      >>> b
      [8, 'str2', 5, 'str1']
      

      同样你也可以将它插入到另一个位置:

      >>> a=[5, 'str1'] 
      >>> b=[8, 'str2'] 
      >>> b[1:1] = a
      >>> b
      [8, 5, 'str1', 'str2']
      

      【讨论】:

        【解决方案3】:

        你可以使用加法:

        >>> a=[5, 'str1']
        >>> b=[8, 'str2'] + a
        >>> b
        [8, 'str2', 5, 'str1']
        

        【讨论】:

        • 这绝对是最好的选择。谢谢
        【解决方案4】:
        >>> a
        [5, 'str1']
        >>> b=[8, 'str2'] + a
        >>> b
        [8, 'str2', 5, 'str1']
        >>> 
        

        对于 extend(),您需要分别定义 b 和 a...

        那么b.extend(a) 就可以了

        【讨论】:

          【解决方案5】:

          做到这一点的有效方法是使用 list 类的 extend() 方法。它将一个可迭代对象作为参数并将其元素附加到列表中。

          b.extend(a)
          

          在内存中创建新列表的其他方法是使用 + 运算符。

          b = b + a
          

          【讨论】:

          • 这绝对是更好的解决方案。
          猜你喜欢
          • 2020-10-29
          • 1970-01-01
          • 2012-05-20
          • 2020-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-08
          相关资源
          最近更新 更多