a break for comprehensions
Tom Jenkins
tjenkins at nospiced.ham.devis.com
Thu Jul 26 11:01:52 EDT 2001
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)
More information about the Python-list
mailing list