在Python中按索引填充列表/数组? [英] Populating a list/array by index in Python?

查看:406
本文介绍了在Python中按索引填充列表/数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?

myList = []

myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'

当我尝试时,我得到:

# IndexError: list assignment index out of range # 

推荐答案

在对它进行索引之前,您必须预先将其填充一些东西(例如0None):

You'll have to pre-fill it with something (e.g. 0 or None) before you can index it:

myList = [None] * 100  # Create list of 100 'None's
myList[12] = 'a'  # etc.

或者,使用字典而不是列表,例如

Alternatively, use a dict instead of a list, as Alex Martelli suggested.

这篇关于在Python中按索引填充列表/数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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