给出两个列表:
x = [1,2,3]
y = [4,5,6]其语法是什么:
x插入到y中,这样y看起来就像将x的所有项插入到y中,这样y看起来就像[1, 2, 3, 4, 5, 6]了
发布于 2010-09-20 08:46:02
你是说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] 发布于 2010-09-20 08:51:49
这个问题并不清楚你到底想要实现什么。
List具有append方法,该方法将其参数附加到list:
>>> 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]列表切片非常灵活,因为它允许用另一个列表中的一系列条目替换列表中的一系列条目:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]发布于 2010-09-20 08:43:51
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]http://docs.python.org/tutorial/datastructures.html
https://stackoverflow.com/questions/3748063
复制相似问题