如何在Python中的特定位置向列表中添加对象?这就是我的意思。
我想把字符串 'String2' 添加到列表中的 x 点,但 x 点并不存在。我如何创建spot x?
我希望它是这样的。
list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)
输出
['String1', None, None, 'String2']
你要找的是一个稀疏的列表,在这个列表中,值可以以任意的索引输入。这个问题 有一些可能的解决方案,比如自定义稀疏列表的实现或者使用dict。
像这样创建你的列表。
initial_size = 4
list = [None] * initial_size
list[0] = 'String1'
list[3] = 'String2'
print(list) # ['String1', None, None, 'String2']
为了增加列表的大小,增加更多的空格。
spaces_to_add = 5
list += [None] * spaces_to_add
print(list) # ['String1', None, None, 'String2', None, None, None, None]
如果你真的想要的话,你可以用这样的东西来做。
def list_add(list_to_add, data, index):
if index < len(list_to_add):
list_to_add[index] = data
else:
while index > len(list_to_add):
list_to_add.append(None)
list_to_add.append(data)
事实上,我不认为这是最好的方法, 你应该使用一个带有整数索引的字典,比如这样。
d = {1: 'String1'}
x = 4
d[x] = 'String2'
它是以哈希表的形式实现的,所以它的查找时间是恒定的。 阅读 本文,关于python词典!
希望对你有所帮助:)
首先,请修正你的索引错误。
x = 4
它不是第四元素,而是第五元素。所以你的代码和结果
['String1', None, None, 'String2']
是不兼容的。
而且你应该记住,链接列表不是一个C型数组,在内存中存储为一行。你应该初始化范围和值,来构造和使用它。考虑作为一个解决方案。
list = ['String1',None,None,None,None]
x = 4
list[x] = 'String2'
#or (where x - the place where to insert, but not the index!):
#list.insert(x, 'String2')
print(list)
当然,你可以用lambda或 "*"来自动生成它。
另一种方法--使用数组或字典,而不是列表,在你的情况下,这听起来是个正确的想法,但你是在向列表寻求帮助。