xrange与itertools.count Python 2.7 [英] xrange versus itertools.count Python 2.7

查看:99
本文介绍了xrange与itertools.count Python 2.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个从开始到结束值的范围.它在较小的数字上工作正常,但是当数字太大时会导致溢出错误,因为int太大而无法转换为C Long.我正在使用Python 2.7.3.

I want to run a range from a start to an end value. It works fine on low numbers but when it gets too large it causes an overflow error as int too large to convert to C Long. I am using Python 2.7.3.

我在这里阅读 OverflowError Python int太大,无法使用itertools.count()方法转换为C long ,只是该方法的作用与xrange方法不同,因为通过步进而不是声明结束范围值.

I read here OverflowError Python int too large to convert to C long on using the itertools.count() method except that method works differently to the xrange method by stepping as opposed to declaring an end range value.

可以将itertools.count()设置为像xrange()一样工作吗?

Can the itertools.count() be set up to work like xrange()?

print "Range start value"
start_value = raw_input('> ')
start_value = int(start_value)

print "Range end value"
end_value = raw_input('> ')
end_value = int(end_value)

for i in xrange(start_value, end_value):
    print hex(i)

推荐答案

您可以使用 在重复end_value - start_value值之后,

islice()会升高StopIteration.

islice() raises StopIteration after end_value - start_value values have been iterated over.

支持非1的步长并将其全部放到函数中将是:

Supporting a step size other than 1 and putting it all together in a function would be:

from itertools import count, islice

def irange(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
    length = 0
    if step > 0 and start < stop:
        length = 1 + (stop - 1 - start) // step
    elif step < 0 and start > stop:
        length = 1 + (start - 1 - stop) // -step
    return islice(count(start, step), length)

然后像使用range()xrange()一样使用irange(),除了现在可以使用Python long整数:

then use irange() like you'd use range() or xrange(), except you can now use Python long integers:

>>> import sys
>>> for i in irange(sys.maxint, sys.maxint + 10, 3):
...     print i
... 
9223372036854775807
9223372036854775810
9223372036854775813
9223372036854775816

这篇关于xrange与itertools.count Python 2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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