简体   繁体   English

我想向空列表的特定索引插入一些元素

[英]I want to insert some element to specific index of empty list

I have s empty array. 我有一个空数组。 For example: base=[] . 例如: base=[] Then i want to insert "Tofiq" string to 3 th element. 然后,我想将"Tofiq"字符串插入第3个元素。 If i use print(base[3]) it must return "Tofiq" string. 如果我使用print(base[3])则必须返回"Tofiq"字符串。 Please help me about it! 请帮助我!

You either have to add intermediate elements to the list or use a dictionary instead of a list. 您要么将中间元素添加到列表中,要么使用字典而不是列表。

 base   = []     
 index  = 3
 base  += [None]*(index-len(base)+1)
 base[index] = "ToFig"

or 要么

 base    = dict()
 base[3] = "ToFig"

list不能有空节点,因此请填充列表,直到所需的索引或使用字典为止

When you assign 'Tofiq' to index 3 of the empty list (for example, base[3] = 'Tofiq' ), it will give IndexError. 当您将'Tofiq'分配给空列表的索引3时(例如, base[3] = 'Tofiq' ),它将给出IndexError。 You should initialize your list instead of creating an empty list. 您应该初始化列表,而不是创建一个空列表。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM