gpt4 book ai didi

python - 在列表中的特定索引处插入元素并返回更新后的列表

转载 作者:IT老高 更新时间:2023-10-28 21:40:35 25 4
gpt4 key购买 nike

我有这个:

>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]

>>> print a.insert(2, 3)
None

>>> print a
[1, 2, 3, 4]

>>> b = a.insert(3, 6)
>>> print b
None

>>> print a
[1, 2, 3, 6, 4]

有没有一种方法可以获得更新的列表作为结果,而不是更新原始列表?

最佳答案

l.insert(index, obj) 实际上并没有返回任何东西。它只是更新列表。

正如 ATO 所说,你可以做到 b = a[:index] + [obj] + a[index:]。但是,另一种方式是:

a = [1, 2, 4]
b = a[:]
b.insert(2, 3)

关于python - 在列表中的特定索引处插入元素并返回更新后的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14895599/

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