我对 Python 很陌生,想找到替代方法来重新创建与列表一起使用的插入方法功能。
>>> ulist = [1,2,3,4,5]
>>> ulist.insert(2,9)
>>> ulist
[1, 2, 9, 3, 4, 5]
>>>
Run Code Online (Sandbox Code Playgroud)
在这里,我想从用户那里获取一个输入列表,然后询问他/她想要放入新值的位置的编号。然后在该位置添加该值,而不会干扰已经存在的列表元素。
>>> ulist = [1,2,3,4,5]
>>> num = int(input("Enter the number: "))
Enter the number: 2
>>> index1 = num - 1
>>> val = int(input("enter the value to be put at index location: "))
enter the value to be put at index location: 9
>>> ulist[index1] = val
>>> print(ulist)
[1, 9, 3, 4, 5]
>>>
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用切片符号。这也具有保持原始列表不变的优点:
>>> ulist = [1,2,3,4,5]
>>> ulist2 = ulist[:2] + [9] + ulist[2:]
>>> ulist2
[1, 2, 9, 3, 4, 5]
>>> ulist
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2201 次 |
| 最近记录: |