如何使用range()在Python中迭代大量数字? [英] How do I iterate over large numbers in Python using range()?

查看:89
本文介绍了如何使用range()在Python中迭代大量数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python中的range()函数来迭代诸如600851475143之类的大量对象.但是,每当我运行该程序时,都会出现OverflowError. 我使用了以下代码-

I want to iterate a large number such as 600851475143 using the range() function in Python. But whenever I run the program it gives me an OverflowError. I have used the following code -

um = long(raw_input())
for j in range(1,num):
....

我已经尝试了很多次,但是没有用!

I have tried it many times but it is not working!

推荐答案

如果索引为长数字,请使用itertools.islice():

Use itertools.islice() if your indices are long numbers:

from itertools import islice, count
islice(count(start, step), (stop-start+step-1+2*(step<0))//step)

Python 3的range()也可以处理python longs.

Python 3's range() can handle python longs as well.

简化为您的情况:

for j in islice(count(1), num - 1):

这篇关于如何使用range()在Python中迭代大量数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆