
On 2013-01-28, at 14:59 , Oscar Benjamin wrote:
On 28 January 2013 13:56, Chris Angelico rosuav@gmail.com wrote:
On Tue, Jan 29, 2013 at 12:33 AM, Wolfgang Maier wolfgang.maier@biologie.uni-freiburg.de wrote:
Why not extend this filtering by allowing a while statement in addition to if, as in:
[n for n in range(1,1000) while n < 400]
The time machine strikes again! Check out itertools.takewhile - it can do pretty much that:
import itertools [n for n in itertools.takewhile(lambda n: n<400, range(1,1000))]
It's not quite list comp notation, but it works.
[n for n in itertools.takewhile(lambda n: n<40, range(1,100))]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
The while clause is a lot clearer/nicer than takewhile/lambda. Presumably it would be more efficient as well.
Maybe, but it's a rather uncommon need and that way lies Common Lisp's `loop`.