在list的同一索引处插入两个或多个值



没有特别询问切片,基本上我想用2个或更多元素替换list的特定索引的值。

例如:

list_a = [1, 2, 3]list_b = [4, 5]所以我想要的是result = [4, 5, 2, 3]

如果你想要一个新的列表:

idx = 0
result = list_a[:idx]+list_b+list_a[idx+1:]

输出:[4, 5, 2, 3]

如果你想修改列表:

idx = 0
list_a[:] = list_a[:idx]+list_b+list_a[idx+1:]
# OR (see @Nineteendo's comment)
list_a[idx:idx + 1] = list_b

一步一步

# get values up to the insertion point
list_a[:idx]
# []
# get values after the insertion point
list_a[idx+1:]
# [2, 3]
# combine everything in a single list
list_a[:idx]+list_b+list_a[idx+1:]
# [4, 5, 2, 3]

您可以使用以下命令实现此操作:首先,您需要弹出0索引值,然后尝试反转b并循环以在0a

索引中插入b的值。
a = [1, 2, 3]
b = [4, 5]
a.pop(0)
for i in b.reverse():
a.insert(0, i)
print(a)

输出:

[4, 5, 2, 3]

最新更新