我正在尝试在Python中设置数组的索引,但它没有按预期运行:
theThing = []
theThing[0] = 0
'''Set theThing[0] to 0'''
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误:
Traceback (most recent call last):
File "prog.py", line 2, in <module>
theThing[0] = 0;
IndexError: list assignment index out of range
Run Code Online (Sandbox Code Playgroud)
在Python中设置数组索引的正确语法是什么?
Python列表没有固定的大小.要设置0th元素,您需要有一个0元素:
>>> theThing = []
>>> theThing.append(12)
>>> theThing
[12]
>>> theThing[0] = 0
>>> theThing
[0]
Run Code Online (Sandbox Code Playgroud)
JavaScript的数组对象与Python的工作方式略有不同,因为它为您填充以前的值:
> x
[]
> x[3] = 5
5
> x
[undefined × 3, 5]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
464 次 |
| 最近记录: |