[Python-Dev] range objects in 3.x

Raymond Hettinger raymond.hettinger at gmail.com
Wed Sep 28 02:28:49 CEST 2011


On Sep 27, 2011, at 3:22 PM, Ethan Furman wrote:

> Well, actually, I'd be using it with dates.  ;)

FWIW, an approach using itertools is pretty general but even it doesn't work for dates :-)

>>> from itertools import count, takewhile
>>> from decimal import Decimal
>>> from fractions import Fraction

>>> list(takewhile(lambda x: x<=10.0, count(0.0, 0.5)))
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]

>>> list(takewhile(lambda x: x<=Decimal(1), count(Decimal(0), Decimal('0.1'))))
[Decimal('0'), Decimal('0.1'), Decimal('0.2'), Decimal('0.3'), Decimal('0.4'), Decimal('0.5'), Decimal('0.6'), Decimal('0.7'), Decimal('0.8'), Decimal('0.9'), Decimal('1.0')]

>>> list(takewhile(lambda x: x<=Fraction(2), count(Fraction(0), Fraction(1,3))))
[Fraction(0, 1), Fraction(1, 3), Fraction(2, 3), Fraction(1, 1), Fraction(4, 3), Fraction(5, 3), Fraction(2, 1)]

>>> from datetime import date, timedelta
>>> list(takewhile(lambda x: x<=date(2011,12,31), count(date(2011,9,27), timedelta(days=7))))

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    list(takewhile(lambda x: x<=date(2011,12,31), count(date(2011,9,27), timedelta(days=7))))
TypeError: a number is required

Raymond
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20110927/b2e63ea8/attachment.html>


More information about the Python-Dev mailing list