简体   繁体   English

如何在python列表中的特定索引处插入元素

[英]how to insert a element at specific index in python list

I am creating a list whose items are to be mapped by index number. 我正在创建一个列表,其项将通过索引号进行映射。 I tried using the list.insert() method. 我尝试使用list.insert()方法。 But still it always adds the first element to 0th index and I want the first element at 1st index. 但是仍然总是将第一个元素添加到第0个索引,而我希望第一个元素位于第一个索引。 For example: 例如:

somelist=[]
somelist.insert(1,"Jack")
somelist.insert(2,"Nick")
somelist.insert(3,"Daniel")

>>print(somelist[1])
Nick # not Jack

how can I do this in Python? 如何在Python中做到这一点? where I can insert element only at given index and let the list start from index 1. 我只能在给定索引处插入元素,然后让列表从索引1开始。

When you insert something into a empty list, it will always be starting from the first position. 当您将某物插入一个空列表时,它总是从第一个位置开始。 Do something like this as workaround: 做这样的解决方法:

somelist=[]
somelist.insert(0,"dummy")
somelist.insert(1,"Jack")
somelist.insert(2,"Nick")
somelist.insert(3,"Daniel")

#print(somelist[1])
print(somelist[1])

output: 输出:

Jack

Your somelist array is empty, which means you can't add an item to the index 1 if there is no item in index 0.. 您的somelist数组为空,这意味着如果索引0中没有任何项,则无法将一项添加到索引1中。

With this i mean when you first try to insert "Jack" to index 1, it goes automatically to index 0, and then you insert "Nick" to index 2, and that goes to index 1... and last you print index 1 which is "Nick" 我的意思是,当您第一次尝试将“ Jack”插入索引1时,它会自动转到索引0,然后将“ Nick”插入索引2,然后转到索引1 ...最后打印索引1这是“尼克”

I think a dictionary could be helpful here if that will do. 我认为如果这样做的话,词典在这里可能会有所帮助。

Like 喜欢

d={}

and insertion at required places is as easy as 并在所需位置插入就像

d[1]="Jack"
d[2]="Nick"
d[3]="Daniel"

Now 现在

print( d[1] )

will print 将打印

Jack

This way you won't have to use dummy values. 这样,您将不必使用伪值。

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

相关问题 如何在特定索引处插入列表? - How to insert a list at a specific index? 在 python 列表中的任意索引处插入一个元素 - Insert an element at an arbitrary index in python list Python - 在不使用插入函数的情况下在特定索引处插入元素 - Python - insert element at specific index without using insert function 在列表中的特定索引处插入元素并返回更新后的列表 - Insert an element at a specific index in a list and return the updated list Python - 仅当列表中存在某些特定元素时才将元素插入列表 - Python - Insert an element to a list only if some specific element exists in the list 如何通过在 python 的列表中仅给出该元素的特定部分来查找列表中元素的索引 - how to find the index of an element in a list by giving only a specific part of that element in a list in python 我想向空列表的特定索引插入一些元素 - I want to insert some element to specific index of empty list 将特定索引处的元素插入列表,覆盖相同索引处的元素或扩展列表 - Insert into list an element at specific index, overwrite the element at same index or expanding list 如何在不使用 python 循环的情况下将元素插入 3d numpy 数组中的特定索引? - How to insert element to a specific index in 3d numpy array without using python loops? Python 列表插入带索引 - Python list insert with index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM