简体   繁体   English

如何在某个索引处将一个列表添加到python中的另一个列表

[英]How to add a list to another list in python at a certain index

For example, how do i do this:例如,我该怎么做:

x=[1,2,3]
y=[4,5,6]
list3=[1,4,5,6,2,3]

i do not want [1,[4,5,6],2,3]我不想要[1,[4,5,6],2,3]

basically i want to extend it, but at a given index基本上我想扩展它,但在给定的索引

Select an empty slice at the index you want, and insert the other list there: Select 在你想要的索引处的一个空切片,并在那里插入另一个列表:

>>> x=[1,2,3]
>>> y=[4,5,6]
>>> x[1:1]=y
>>> x
[1, 4, 5, 6, 2, 3]

Use slice assignment.使用切片赋值。

list3 = x[:] # make copy of x
list3[1:1] = y # replace empty slice at index 1 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM