如何传播python数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48451228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to spread a python array
提问by Alex Cory
In JS I can do this
在 JS 我可以做到这一点
const a = [1,2,3,4]
const b = [10, ...a]
console.log(b) // [10,1,2,3,4]
Is there a similar way in python?
python中有类似的方法吗?
回答by Adam Smith
As Alexander points out in the comments, list addition is concatenation.
正如亚历山大在评论中指出的那样,列表添加是连接。
a = [1,2,3,4]
b = [10] + a # N.B. that this is NOT `10 + a`
# [10, 1, 2, 3, 4]
You can also use list.extend
你也可以使用 list.extend
a = [1,2,3,4]
b = [10]
b.extend(a)
# b is [10, 1, 2, 3, 4]
and newer versions of Python allow you to (ab)use the splat (*
) operator.
和更新版本的 Python 允许您(ab)使用 splat ( *
) 运算符。
b = [10, *a]
# [10, 1, 2, 3, 4]
Your choice may reflect a need to mutate (or not mutate) an existing list, though.
不过,您的选择可能反映了改变(或不改变)现有列表的需要。
a = [1,2,3,4]
b = [10]
DONTCHANGE = b
b = b + a # (or b += a)
# DONTCHANGE stays [10]
# b is assigned to the new list [10, 1, 2, 3, 4]
b = [*b, *a]
# same as above
b.extend(a)
# DONTCHANGE is now [10, 1, 2, 3, 4]! Uh oh!
# b is too, of course...
回答by Alex Cory
Python's list object has the .extend
function.
Python 的 list 对象就有这个.extend
功能。
You can use it like this:
你可以这样使用它:
a = [1, 2, 3, 4]
b = [10]
b.extend(a)
print(b)
回答by Francisco Jiménez Cabrera
The question does not make clear what exactly you want to achieve.
这个问题并没有说明你到底想要达到什么目的。
There's also the extend method, which appends items from the list you pass as an argument:
还有 extend 方法,它从您作为参数传递的列表中附加项目:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
To extend a list at a specific insertion point you can use list slicing:
要在特定插入点扩展列表,您可以使用列表切片:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]