Cleaning up conditionals
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Sun Jan 1 03:01:14 EST 2017
Steve D'Aprano writes:
> On Sun, 1 Jan 2017 02:58 pm, Deborah Swanson wrote:
>
>>> It's possible to select either l1 or l2 using an expression,
>>> and then subscript that with [v]. However, this does not
>>> usually make for readable code, so I don't recommend it.
>>>
>>> (l1 if whatever else l2)[v] = new_value
>>>
>>> ChrisA
>>
>> I'm not sure I understand what you did here, at least not well enough
>> to try it.
>
>
> The evolution of a Python programmer :-)
>
>
> (1) Step One: the naive code.
>
> if condition:
> l1[v] = new_value
> else:
> l2[v] = new_value
>
>
> (2) Step Two: add a temporary variable to avoid repeating the
> assignment
>
> if condition:
> temp = l1
> else:
> temp = l2
> temp[v] = new_value
>
>
> (3) Step Three: change the if...else statement to an expression
>
> temp = l1 if condition else l2
> temp[v] = new_value
>
>
> (4) Step Four: no need for the temporary variable
>
> (l1 if condition else l2)[v] = new_value
(l1 if bool(l1[v]) < bool(l2[v]) else
l2 if bool(l1[v]) > bool(l2[v]) else
l1)[v] = (l2 if bool(l1[v]) < bool(l2[v]) else
l1 if bool(l1[v]) > bool(l2[v]) else
l1)[v]
Merry new year :)
More information about the Python-list
mailing list