問題描述
如何解決python限制數組長度 (How to solve python limited array length)
我在使用 32 位版本 Python 的 32 位機器上。
當我嘗試創建一個大數組時,當我的數組長度為 5592406 時出現以下錯誤
:
Traceback (most recent call last): File "/root/PycharmProjects/stackidiots/main.py", line 3, in <module> dd [x] = x IndexError: list assignment index out of range
是 Python 的限制還是我的代碼有問題?這是我的代碼:
dd = []
for x in range(5592406):
dd [x] = x
那麼如何解決這個問題呢?如果我切換到 64 位,它會變得更大嗎?
參考解法
方法 1:
No it is not a limit in Python's ability.
Rather, you have made an error in your code.
You'll notice that your error says:
IndexError: list assignment index out of range
Note the list assignment piece. You are trying to assign x to an indice in the list that doesn't exist yet. When you do dd [x] = x
.
Instead, just append x to the list with list.append(value)
dd = []
for x in range(5592406):
dd.append(x)
Although this works, it is cumbersome and can be more easily done on one line with a list comprehension.
dd = [x for x in range(5592406)]
方法 2:
The shortest solution to your problem is:
dd = list(range(5592406))
This works for Python 2 and 3.
The error message:
IndexError: list assignment index out of range
Tells you that you try to assign to an index that does not (yet) exist. This has nothing to do with 32 or 64‑bit version of Python.
(by Ryan Arief、Jason、Mike Müller)