a break for comprehensions
Nick Perkins
nperkins7 at home.com
Thu Jul 26 12:55:57 EDT 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
one.
>
>
> do you mean like this?
> >>> def even(x):
> ... return int(divmod(x,2)[1]) == 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)
> '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.
ie.
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
def conditional_iter(lst,cond):
for item in lst:
if cond(item):
yield item
else:
raise StopIteration
mylist = [0,2,4,5,6]
def even(num): return not (num%2)
for num in conditional_iter(mylist, even)
print num
More information about the Python-list
mailing list