在Python中,是否可以模仿JavaScript数组(即,当将值添加到数组范围之外时会自动扩展的数组)?在JavaScript中,当在数组的索引之外分配值时,数组会自动展开,但在Python中,它们不会:

theArray = [None] * 5
theArray[0] = 0
print(theArray)
theArray[6] = 0 '''This line is invalid. Python arrays don't expand automatically, unlike JavaScript arrays.'''


这将在JavaScript中有效,并且我正在尝试在Python中模仿它:

var theArray = new Array();
theArray[0] = 0;
console.log(theArray);
theArray[6] = 0; //the array expands automatically in JavaScript, but not in Python

最佳答案

如果您确实需要,可以定义以下结构:

class ExpandingList(list):
    def __setitem__(self, key, value):
        try:
            list.__setitem__(self, key, value)
        except IndexError:
            self.extend((key - len(self)) * [None] + [value])

>>> a = ExpandingList()
>>> a[1] = 4
>>> a
[None, 4]
>>> a[4] = 4
>>> a
[None, 4, None, None, 4]


将其与其他python功能集成可能很棘手(负索引,切片)。

09-18 05:50