如果索引不存在,则 Python 列表在索引处设置值 [英] Python list set value at index if index does not exist
本文介绍了如果索引不存在,则 Python 列表在索引处设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法、lib 或 python 中的某些东西可以在不存在的索引处设置列表中的值?类似于在列表中创建运行时索引:
Is there a way, lib, or something in python that I can set value in list at an index that does not exist? Something like runtime index creation at list:
l = []
l[3] = 'foo'
# [None, None, None, 'foo']
更进一步,多维列表:
l = []
l[0][2] = 'bar'
# [[None, None, 'bar']]
或者使用现有的:
l = [['xx']]
l[0][1] = 'yy'
# [['xx', 'yy']]
推荐答案
没有内置,但很容易实现:
There isn't a built-in, but it's easy enough to implement:
class FillList(list):
def __setitem__(self, index, value):
try:
super().__setitem__(index, value)
except IndexError:
for _ in range(index-len(self)+1):
self.append(None)
super().__setitem__(index, value)
或者,如果您需要更改现有的原版列表:
Or, if you need to change existing vanilla lists:
def set_list(l, i, v):
try:
l[i] = v
except IndexError:
for _ in range(i-len(l)+1):
l.append(None)
l[i] = v
这篇关于如果索引不存在,则 Python 列表在索引处设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文