Mat*_*que 5 python list python-3.x
所以我想列出一个列表:
[1, 2, 3, 4]
然后在位置“i”之前添加一个项目。例如,如果 i = 2,列表将变为:
[1, 2, "desired number", 3, 4]
我怎么能在python中做到这一点?先谢谢了。
Insert 是一个明智的选择,您也可以使用列表推导式(切片)。
根据您想要插入的不均匀项目列表的哪一侧,您可能想要使用
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]
Run Code Online (Sandbox Code Playgroud)
或者
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12368 次 |
| 最近记录: |