xrange与itertools.count Python 2.7

时间:2014-12-28 10:47:03

标签: python python-2.7 itertools xrange

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

我在这里使用itertools.count()方法阅读OverflowError Python int too large to convert to C long,但该方法的工作方式与xrange方法不同,而不是声明结束范围值。

可以将itertools.count()设置为像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)

1 个答案:

答案 0 :(得分:4)

您可以使用itertools.islice()count提供结束:

from itertools import count, islice

for i in islice(count(start_value), end_value - start_value):
在迭代islice()值后,

StopIteration会提升end_value - start_value

支持1以外的步长并将其全部放在一个函数中将是:

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)

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

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