Conditional iteration
at
at at tuko.nl
Wed Dec 13 17:34:15 EST 2006
No offense, but my conclusions from your mail is that readability is a
matter of taste.
My brains need to process a whole lot more information with your solution
than in my proposal...
but I read somewhere else that GvR rejected the proposal :-(
Ciao,
@
shandy.b at gmail.com wrote:
> The proposed solution impairs readability because there's a "surprise"
> at the end. List comprehensions already open the language up to
> readability abuse. Lets not add more.
>
> To avoid the unwanted indentation, I would go with the already
> suggested "if not x>0: continue" solution or else something like this:
>
> positiveMembers = [x for x in [-2, -1, 0, 1, 2, 3, 4] if x>0]
> for x in positiveMembers:
> #do stuff
>
> This has the advantage of being more self-documenting.
>
> at wrote:
>> I would like to spark the discussion about the following syntax problem I
>> encounter.
>>
>> THE PROBLEM
>>
>> I have a lot times the following code:
>>
>> for x in [-2, -1, 0, 1, 2, 3, 4]:
>> if x > 0:
>> ... more code...
>>
>>
>> It is not the addional line containing 'if x > 0:' that bothers me, but
>> the additional indentation.
>>
>>
>> THE SOLUTION
>>
>> More pythonic in view would be:
>>
>> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0:
>> ... more code ...
>>
>>
>> This blends basically
>>
>> [x for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0]
>>
>> and
>>
>> x = y if x > 0 else 10
>>
>>
>> EXTENDING
>>
>> And maybe a few usefull variants, like:
>>
>> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0 else -x:
>> ... more code ...
>>
>> In this case x will be 2, 1, 0, 1, 2, 3, 4.
More information about the Python-list
mailing list