如果索引不存在,则 Python 列表在索引处设置值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22388866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python list set value at index if index does not exist
提问by user1538560
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:
有没有办法,lib 或 python 中的某些东西,我可以在不存在的索引处设置列表中的值?类似于在列表中创建运行时索引:
l = []
l[3] = 'foo'
# [None, None, None, 'foo']
And more further, with multi dimensional lists:
更进一步,使用多维列表:
l = []
l[0][2] = 'bar'
# [[None, None, 'bar']]
Or with an existing one:
或者使用现有的:
l = [['xx']]
l[0][1] = 'yy'
# [['xx', 'yy']]
采纳答案by jonrsharpe
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
回答by Drewness
You cannot create a list with gaps. You could use a dictor this quick little guy:
您不能创建有间隙的列表。你可以使用一个dict或这个快速的小家伙:
def set_list(i,v):
l = []
x = 0
while x < i:
l.append(None)
x += 1
l.append(v)
return l
print set_list(3, 'foo')
>>> [None, None, None, 'foo']
回答by Corley Brigman
If you really want the syntax in your question, defaultdictis probably the best way to get it:
如果您真的想要问题中的语法,defaultdict这可能是获得它的最佳方法:
from collections import defaultdict
def rec_dd():
return defaultdict(rec_dd)
l = rec_dd()
l[3] = 'foo'
print l
{3: 'foo'}
l = rec_dd()
l[0][2] = 'xx'
l[1][0] = 'yy'
print l
<long output because of defaultdict, but essentially)
{0: {2: 'xx'}, 1: {0: 'yy'}}
It isn't exactly a 'list of lists' but it works more or less like one.
它不完全是一个“列表列表”,但它或多或少地像一个列表。
You really need to specify the use case though... the above has some advantages (you can access indices without checking whether they exist first), and some disadvantages - for example, l[2]in a normal dict will return a KeyError, but in defaultdictit just creates a blank defaultdict, adds it, and then returns it.
您确实需要指定用例……上面有一些优点(您可以访问索引而无需先检查它们是否存在),也有一些缺点 - 例如,l[2]在普通 dict 中将返回 a KeyError,但在defaultdict它只是创建一个空白defaultdict,添加它,然后返回它。
Other possible implementations to support different syntactic sugars could involve custom classes etc, and will have other tradeoffs.
支持不同语法糖的其他可能实现可能涉及自定义类等,并且会有其他权衡。
回答by tegan
Not foolproof, but it seems like the easiest way to do this is to initialize a list much larger than you will need, i.e.
并非万无一失,但似乎最简单的方法是初始化一个比您需要的大得多的列表,即
l = [None for i in some_large_number]
l[3] = 'foo'
# [None, None, None, 'foo', None, None None ... ]

