a break for comprehensions
nperkins7 at home.com
Thu Jul 26 18:55:57 CEST 2001
"Tom Jenkins" <tjenkins at nospiced.ham.devis.com> wrote in message
news:3B6031C3.6010707 at nospiced.ham.devis.com...
> Kevin Lacker wrote:
> > Can you do this:
> > answer = 
> > for x in my_list:
> > if not is_good(x):
> > break
> > answer.append(process(x))
> > with a list comprehension somehow? I'm starting to dislike explicit for
> > loops just for the purposes of constructing another list from a current
> do you mean like this?
> >>> def even(x):
> ... return int(divmod(x,2)) == 0
> >>> a = [1, 2, 3, 4, 5, 6, 7]
> >>> b = [z for z in a if not even(z)]
> >>> print b
> [1, 3, 5, 7]
> >>> c = [z for z in a if even(z)]
> >>> print c
> [2, 4, 6]
> oops sorry just saw that you had process(x) in there... lets try it:
> >>> def process(x):
> ... return str(x)
> >>> process(1)
> >>> c = [process(z) for z in a if even(z)]
> >>> print c
> ['2', '4', '6']
> hmmm, seems to work for me (python 2.1)
This misses the point of the original post.
Notice the 'break' in the original for-loop version.
The idea is to return consecutive elements,
up to, but not including, the first element which
does not meet the condition.
lst = [0,2,4,5,6]
evens = [0,2,4]
I don't think list comprehensions can do this.
Here's a generator approach to the problem:
from __future__ import generators
for item in lst:
mylist = [0,2,4,5,6]
def even(num): return not (num%2)
for num in conditional_iter(mylist, even)
More information about the Python-list