在Python中插入一个列表到另一个列表的语法是什么?
给出两个列表:
x = [1,2,3] y = [4,5,6] 
什么是语法:
-  在
y插入x使得y现在看起来像[1, 2, 3, [4, 5, 6]]? -  插入
x所有项目,使y现在看起来像[1, 2, 3, 4, 5, 6]? 
 你的意思是append ? 
 >>> x = [1,2,3] >>> y = [4,5,6] >>> x.append(y) >>> x [1, 2, 3, [4, 5, 6]] 
还是合并?
 >>> 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] 
这个问题没有说明你想达到什么目的。
  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]] 
 还有一个extend方法,它将您传递的参数中的项目作为参数添加进来: 
 >>> list_one = [1,2,3] >>> list_two = [4,5,6] >>> list_one.extend(list_two) >>> list_one [1, 2, 3, 4, 5, 6] 
 当然,还有一个insert方法,其作用类似于append但允许您指定插入点: 
 >>> list_one.insert(2, list_two) >>> list_one [1, 2, [4, 5, 6], 3, 4, 5, 6] 
要在特定插入点处扩展列表,可以使用列表切片(谢谢,@florisla):
 >>> l = [1, 2, 3, 4, 5] >>> l[2:2] = ['a', 'b', 'c'] >>> l [1, 2, 'a', 'b', 'c', 3, 4, 5] 
列表切片是非常灵活的,因为它允许使用另一个列表中的一系列条目replace列表中的一系列条目:
 >>> l = [1, 2, 3, 4, 5] >>> l[2:4] = ['a', 'b', 'c'][1:3] >>> l [1, 2, 'b', 'c', 5] 
 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] 
如果要将列表(列表2)中的元素添加到其他列表(列表)的末尾,则可以使用列表扩展方法
 list = [1, 2, 3] list2 = [4, 5, 6] list.extend(list2) print list [1, 2, 3, 4, 5, 6] 
或者,如果你想连接两个列表,那么你可以使用+符号
 list3 = list + list2 print list3 [1, 2, 3, 4, 5, 6]