如何解決python限制數組長度 (How to solve python limited array length)


問題描述

如何解決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 AriefJasonMike Müller)

參考文件

  1. How to solve python limited array length (CC BY‑SA 2.5/3.0/4.0)

#Python #arrays






相關問題

如何從控制台中導入的文件中訪問變量的內容? (How do I access the contents of a variable from a file imported in a console?)

在 python 3.5 的輸入列表中添加美元符號、逗號和大括號 (Adding dollar signs, commas and curly brackets to input list in python 3.5)

為 KeyError 打印出奇怪的錯誤消息 (Strange error message printed out for KeyError)

django 1.9 中的 from django.views.generic.simple import direct_to_template 相當於什麼 (What is the equivalent of from django.views.generic.simple import direct_to_template in django 1.9)

查詢嵌入列表中的數組 (Querying for array in embedded list)

如何在 Python 中搜索子字符串是否在二進製文件中? (How to search if a substring is into a binary file in Python?)

為什麼要避免 while 循環? (Why avoid while loops?)

使用python的json模塊解析json請求 (Parse a json request using json module of python)

為什麼使用 py2app 模塊創建 mac 文件時出現錯誤? (Why i am getting Error when creating mac file using py2app module?)

當 python 線程在網絡調用(HTTPS)中並且發生上下文切換時會發生什麼? (What happens when the python thread is in network call(HTTPS) and the context switch happens?)

如何繪製一條帶斜率和一個點的線?Python (How to plot a line with slope and one point given? Python)

Pickle 找不到我不使用的模塊? (Pickle can't find module that I am not using?)







留言討論