On Thu, Apr 26, 2012 at 10:02 AM, Roy Smith <[email protected]> wrote:
>
> I'm not seriously suggesting this as a language addition, just an interesting
> idea to simplify some code I'm writing now:
>
> x = [a for a in iterable while a]
>
> which equates to:
>
> x = []
> for a in iterable:
> if not a:
> break
> x.append(a)
>
> It does has a few things going for it. It doesn't add any new keywords, nor
> does it change the meaning of any currently valid program. Whether it's
> sufficiently useful in general is another question :-) In the specific case
> I'm looking at now, I've got this annoying lump of code:
>
> valid_answers = []
> for p in pairs:
> if not all(p):
> break
> valid_answers.append(p)
>
> which could be rewritten as:
>
> valid_answers = [p for p in pairs while all(p)]
>
> pairs is a list of tuples. I need the leading portion of the list where all
> elements of the tuple are string non-zero-length strings. Obviously, you'd
> do the corresponding generator expression as well.
It could also be written as:
itertools.takewhile(all, pairs)
http://docs.python.org/library/itertools.html#itertools.takewhile
>
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list