我想要实现的功能是在一个列表中:
[1, 2, 3, 4]
在第i个位置之前添加一个新的元素。例如,如果i = 2,那么列表将变为:
[1, 2, "期望添加的数字", 3, 4]
我应该如何用Python实现它?谢谢。
我想要实现的功能是在一个列表中:
[1, 2, 3, 4]
在第i个位置之前添加一个新的元素。例如,如果i = 2,那么列表将变为:
[1, 2, "期望添加的数字", 3, 4]
我应该如何用Python实现它?谢谢。
插入
是个明智的选择,你也可以使用列表推导式(切片)。
根据你想要在不对称项列表的哪一侧进行插入,你可能需要使用
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]
>>> l = [1, 2, 3, 4]
>>> add = 5
>>> l[:len(l)//2] + [add] + l[len(l)//2:]
[1, 2, 5, 3, 4]