Com*_*er7 180 python list append extend
给出两个列表:
x = [1,2,3]
y = [4,5,6]
Run Code Online (Sandbox Code Playgroud)
语法是什么:
x到y这样y现在看起来像[1, 2, 3, [4, 5, 6]]?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)
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)
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
| 归档时间: |
|
| 查看次数: |
243394 次 |
| 最近记录: |