[英]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.