在Python中模拟JavaScript数组
在Python中,是否可以模仿JavaScript数组i。e、 ,在数组范围之外添加值时自动展开的数组?在JavaScript中,当在数组索引之外分配值时,数组会自动扩展,但在Python中,数组不会:在Python中模拟JavaScript数组,javascript,python,arrays,Javascript,Python,Arrays,在Python中,是否可以模仿JavaScript数组i。e、 ,在数组范围之外添加值时自动展开的数组?在JavaScript中,当在数组索引之外分配值时,数组会自动扩展,但在Python中,数组不会: theArray = [None] * 5 theArray[0] = 0 print(theArray) theArray[6] = 0 '''This line is invalid. Python arrays don't expand automatically, unlike Java
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
我想不出实现这一点的本地方式。这么说来,仅仅创建一个满足您期望的函数并不是一个坏主意。不使用my_list[index]=值,您可以使用以下内容:
def insertWithAutoFill(the_list, index, new_item):
if index >= len(the_list):
for i in range(len(the_list), index):
the_list.append(None)
the_list.append(new_item)
else:
the_list[index] = new_item
你会这样称呼它:
my_list = [1, 2, 3]
insertWithAutoFill(my_list, 6, 23)
my_列表现在包含:
[1, 2, 3, None, None, None, 23]
您可能需要调整某些内容,以确保正确检查了某些内容,并且正确使用了索引。这是经过少量测试并在特定情况下运行的,但不能保证它是完美的:如果您确实需要,您可以定义这样的结构:
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功能集成在一起可能是一件棘手的事情,比如负索引、切片。,但我将发布本文,向您展示如何为get复制行为
是否有理由需要填写超出范围的索引?还有为什么你需要自动完成而不能自己完成?我相信你只是好奇,但我对你的工作也很好奇intent@Ian这是因为我正在尝试将一个JavaScript库移植到Python,我需要在Python中找到一种类似JavaScript数组的对象类型。我不确定您是否能找到什么。再说一次,我相信有人会想到一些我们忘记的事情。但就像我说的,有什么理由不能创建一个满足您需要的新函数吗?不要只说python_list[100]=随便什么,你必须用autofillpython_list,100,随便什么来做insertWithAutoFillpython_list。我刚刚写了一个简单的函数来实现这一点。这是否是使用/实施的问题?要么就是这样,要么创建自己的类,模仿列表,将此特殊功能作为method@Ian这可能是解决我这里问题的好办法。函数的源代码是否公开?只需在代码中添加一个答案。它不是100%正确,但我仍然在用不同的场景和其他东西进行测试——我只是用fastNice编写了它。这就是我希望能够理解/记住Python的内容。这并不重要,但我认为处理切片会很容易!除非你的意思是endIndex大于列表的长度。对于getter来说是个好主意:在setter中进行额外的检查!很好,但我会以请求原谅的方式实现getter,除了indexer之外,也不会以允许的方式实现getter。您将获得更一致的类型错误。目前,对于a=MyList[0],您有一个[1.0]没有返回,还有一个[0.0]提升。谢谢@zch。更改为请求原谅,固定了浮动和字符串,添加了实现括号表示法的示例。我知道返回在setter上没有什么作用,但我只是复制了JavaScript。
class MyList(list):
@property
def length(self): # for the example bracket notation
return len(self)
def __getitem__(self, key): # Fix GET
try: # assume permission
return list.__getitem__(self, key)
except (IndexError, TypeError): # "ask forgiveness"
pass # using pass to save indents as try was a return
if key == 'length': # example bracket notation for length getter
return self.length
try: # JavaScript doesn't care about number type and accepts
key = int(key) # strings, too, but Python req.s integers
return list.__getitem__(self, int(key))
except (IndexError, ValueError):
pass
return None
def __setitem__(self, key, value): # Fix SET
try:
list.__setitem__(self, key, value)
return value # copy return behaviour
except (IndexError, TypeError):
pass
try:
key = int(key) # force int
except ValueError:
return # fail quietly?
if key < 0: # still throw for bad key
raise IndexError()
self.extend((key - len(self)) * [None]) # fill gap with None
self.append(value) # append new value
return value # copy return behaviour
>>> a = MyList()
>>> a[0] = 1
>>> a[2] = 1
>>> (a, a[3])
([1, None, 1], None)
>>> (a.length, a['length'])
(3, 3)