在 Python (2.7.4) 中使用 range() 时出现内存错误 [英] MemoryError while using range() in Python (2.7.4)
问题描述
好的,我在 StackOverflow 上问了很多关于 MemoryError 的问题,但没有找到满意的答案.我在带有 2GB RAM 的笔记本电脑上运行 Ubuntu 13.04 Gnome 64 位.当我编写以下 Python 代码时 -
Okay, I went through many questions on StackOverflow regarding MemoryError but could not find a satisfactory answer. I'm running Ubuntu 13.04 Gnome 64-bit on my laptop with 2GB RAM. When I write the following Python code -
range(987654321/2)
它抛出一个内存错误.现在我想这可能是由于我的笔记本电脑上的可用内存较少.我的疑问是这取决于是否 -
It throws a MemoryError. Now I suppose that could be due to less available RAM on my laptop. My doubt is does it depend on whether -
- 我有 32 位或 64 位版本的 Python?
- 32 位还是 64 位 Ubuntu?
- 如果我完全在 Windows (ActivePython) 上运行它?
推荐答案
如果您使用的是 Python2.x,请改用 xrange,因为它是一个生成器,不会在内存中创建整个范围,而是根据需要创建每次迭代.
If you are on Python2.x, use xrange instead as it is a generator and will not create the entire range in memory, but instead create each iteration as needed.
这篇关于在 Python (2.7.4) 中使用 range() 时出现内存错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!