在python中将一个列表插入另一个列表的语法是什么?

Com*_*er7 180 python list append extend

给出两个列表:

x = [1,2,3]
y = [4,5,6]
Run Code Online (Sandbox Code Playgroud)

语法是什么:

  1. 插入xy这样y现在看起来像[1, 2, 3, [4, 5, 6]]
  2. 插入的所有项目x进入y,使得y现在的样子[1, 2, 3, 4, 5, 6]

Pao*_*ino 342

你的意思是append

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

还是合并?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6] 
Run Code Online (Sandbox Code Playgroud)

  • x.extend(y)就位,x + y返回新列表。这里没有提到的x + = y与扩展类似。 (5认同)
  • 这是否到位或产生新的实例? (3认同)

Ser*_*gey 71

问题并不清楚你想要实现什么.

List有append方法,它将其参数附加到列表:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

还有extend一种方法,它将您传递的列表中的项目作为参数附加:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

当然,这种insert方法的行为类似,append但允许您指定插入点:

>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

要在特定插入点扩展列表,可以使用列表切片(谢谢,@ florisla):

>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

列表切片非常灵活,因为它允许使用另一个列表中的一系列条目替换列表中的一系列条目:

>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]
Run Code Online (Sandbox Code Playgroud)

  • 如果要"扩展"到特定插入点,可以使用列表切片语法(请参阅http://stackoverflow.com/a/7376026/1075152) (30认同)
  • @ florisla的评论应该是公认的答案.这是将列表插入到任意位置(不仅仅是最后)的另一个列表的唯一方法. (4认同)
  • @weaver虽然这是唯一的解决方案*那个*(在特定索引处扩展),但这不是最初的问题。 (2认同)

Cod*_*ict 30

foo = [1, 2, 3]
bar = [4, 5, 6]

foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

http://docs.python.org/tutorial/datastructures.html