如果索引不存在,则Python列表在索引处设置值

时间:2014-03-13 19:23:16

标签: python python-3.x multidimensional-array

在python中是否有一种方法,lib或其他东西,我可以在不存在的索引中设置列表中的值? 像列表中的运行时索引创建一样:

l = []
l[3] = 'foo'
# [None, None, None, 'foo']

更进一步,使用多维列表:

l = []
l[0][2] = 'bar'
# [[None, None, 'bar']]

或使用现有的:

l = [['xx']]
l[0][1] = 'yy'
# [['xx', 'yy']]

4 个答案:

答案 0 :(得分:7)

没有内置功能,但实施起来非常简单:

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)

或者,如果您需要更改现有的香草列表:

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

答案 1 :(得分:1)

您无法创建包含间隙的列表。你可以使用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']

答案 2 :(得分:1)

如果你真的想要问题中的语法,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'}}

它不完全是'列表列表',但它或多或少与一个列表一样。

你真的需要指定用例虽然......上面有一些优点(你可以访问索引而不检查它们是否先存在),还有一些缺点 - 例如,普通字典中的l[2]会返回KeyError,但在defaultdict中,它只会创建一个空白defaultdict,添加它,然后返回它。

支持不同语法糖的其他可能实现可能涉及自定义类等,并将进行其他权衡。

答案 3 :(得分:1)

并非万无一失,但似乎最简单的方法是初始化一个比您需要的大得多的列表,即

l = [None for i in some_large_number]
l[3] = 'foo'
# [None, None, None, 'foo', None, None None ... ]