将对象插入到特定列表索引 [英] Insert object to specific list index

查看:60
本文介绍了将对象插入到特定列表索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中的特定位置将对象添加到列表中?这就是我的意思:

How can I add an object to a list at a specific spot in Python? This is what I mean:

我想添加字符串'String2'到列表中的 x 位置,但是不存在 x 位置.如何创建现货 x ?

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

我希望它像这样:

list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)

输出:

['String1', None, None, 'String2']

推荐答案

您正在寻找的是稀疏列表,可以在任意索引处输入值.这个问题具有一些可能的解决方案,例如自定义稀疏列表实现或使用dict.

What you're looking for is a sparse list, where values can be entered at arbitrary indices. This question has some possible solutions, like a custom sparse list implementation or using a dict.

这篇关于将对象插入到特定列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆