gpt4 book ai didi

python - 如何传播python数组

转载 作者:行者123 更新时间:2023-12-03 14:39:46 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I concatenate two lists in Python?

(28 个回答)


3年前关闭。




在 JS 我可以做到这一点

const a = [1,2,3,4]
const b = [10, ...a]
console.log(b) // [10,1,2,3,4]

python中有类似的方法吗?

最佳答案

正如亚历山大在评论中指出的那样,列表添加是连接。

a = [1,2,3,4]
b = [10] + a # N.B. that this is NOT `10 + a`
# [10, 1, 2, 3, 4]

您也可以使用 list.extend
a = [1,2,3,4]
b = [10]
b.extend(a)
# b is [10, 1, 2, 3, 4]

和更新版本的 Python 允许您 (ab) 使用 splat ( * ) 运算符。
b = [10, *a]
# [10, 1, 2, 3, 4]

不过,您的选择可能反射(reflect)了改变(或不改变)现有列表的需要。
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...

关于python - 如何传播python数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com