簡體   English   中英

Python迭代器內存錯誤

[英]Python iterator Memory error

我正在運行這個程序來創建一個迭代器但是在它開始打印任何東西之前我都遇到了內存錯誤。

def test():
        for x in range(10000000000000):
                yield x

for x in test():
        print 'hi'

輸出:

tutorial@p1980:~/tej$ python itertest.py
Traceback (most recent call last):
  File "itertest.py", line 7, in <module>
    for x in test():
  File "itertest.py", line 4, in test
    for x in range(10000000000000):
MemoryError

您似乎使用的是Python 2.在這種情況下,請使用xrange()而不是range() xrange()函數返回一個像迭代器而不是列表一樣工作的對象。

在Python 3中, range()返回一個像迭代器一樣工作的對象,並且不提供xrange()函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM