在Python中向列表中间添加项目

10

我想要实现的功能是在一个列表中:

[1, 2, 3, 4]

在第i个位置之前添加一个新的元素。例如,如果i = 2,那么列表将变为:

[1, 2, "期望添加的数字", 3, 4]

我应该如何用Python实现它?谢谢。


3
尝试一些研究...https://docs.python.org/2/tutorial/datastructures.html#more-on-lists - L_Church
2个回答

9

插入是个明智的选择,你也可以使用列表推导式(切片)。

根据你想要在不对称项列表的哪一侧进行插入,你可能需要使用

lst = [1, 2, 3, 4, 7, 8, 9]

midpoint = len(lst)//2        # for 7 items, after the 3th

lst = lst[0:midpoint] + [5] + lst[midpoint:]  

print (lst) # => [1, 2, 3, 5, 4, 7, 8, 9]

或者
lst = [1, 2, 3, 4, 7, 8, 9]

midpoint = len(lst)//2+1      # for 7 items, after the 4th

lst = lst[0:midpoint] + [5] + lst[midpoint:] 

print (lst) # => [1, 2, 3, 4, 5, 7, 8, 9]

3
只需在列表的中间进行分割,并在这些分割之间添加您想要添加的数字:
>>> l = [1, 2, 3, 4]
>>> add = 5
>>> l[:len(l)//2] + [add] + l[len(l)//2:]
[1, 2, 5, 3, 4]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接