Speaking of list-comprehension?

Chinook chinook.nr at tds.net
Fri Jul 1 03:26:20 EDT 2005


Thank you all for taking the time to consider and respond.


I had received the answer OL and responded with:


> Thank you,  and your elaboration is well taken.  I was just exploring here and the construct you noted is IMHO intuitively readable - at least  for a simple  expression  and  condition.  Other than the choice order [False, True] which seems backward to me.
> 
> So, where might I have found this construct.  It is probably somewhere obvious, but I searched and searched without success.  Of course, I've had only limited success in finding what I wanted in the "official' docs, though the QR has been quite useful. 
> Thanks again,
> Lee C
> 
> ==============================================
>>>> ta = [5, 15, 12, 10, 9]
>>>> nta = [tai+[10,-10][tai>=10]for tai in ta]
>>>> nta
> [15, 5, 2, 0, 19]
>>>> ota = [tai+[10,-10][tai>=10]for tai in nta]
>>>> ota
> [5, 15, 12, 10, 9]
> ===============================================



The reply also included some advice which I include for someone else's 
benefit that might find this thread in the future.  I leave the author's 
name out in case anonymity was desired (got in trouble that way once 
:~), not because I don't appreciate the reply.

>>
>>>>> [tai + [10, -10][tai >= 10] for tai in ta]
>>>>>       
>>
>> [15, 5, 2, 0, 19]
>>
>> However, if you find yourself wanting to do simple expressions like
>> this in list comprehensions a lot, you should probably define a helper
>> function:
>>
>>  
>>
>>>>> def iif(expr, trueexpr, falseexpr):
>>>>>       
>>
>> ...     if expr: return trueexpr
>> ...     return falseexpr
>> ...
>>  
>>
>>>>> [tai + iif(tai >= 10, -10, 10) for tai in ta]
>>>>>       
>>
>> [15, 5, 2, 0, 19]
>>
>> If your expression gets much more complex, then you're much better off
>> defining a separate function to do the whole thing, which will keep
>> things readable, even if it doesn't make things more compact:
>>
>>  
>>
>>>>> def adjust(x):
>>>>>       
>>
>> ...     if x >= 10:
>> ...             return x - 10
>> ...     else:
>> ...             return x + 10
>> ...
>>  
>>
>>>>> [adjust(tai) for tai in ta]
>>>>>       
>>
>> [15, 5, 2, 0, 19]
>>




More information about the Python-list mailing list