gpt4 book ai didi

javascript - 在 Python 中模仿 JavaScript 数组

转载 作者:行者123 更新时间:2023-11-28 12:01:26 26 4
gpt4 key购买 nike

在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 功能集成可能会很棘手(负索引、切片)。

关于javascript - 在 Python 中模仿 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15845676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com