Cleaning up conditionals

Deborah Swanson python at deborahswanson.net
Sat Dec 31 17:03:05 EST 2016


Jussi Piitulainen wrote:
> Sent: Saturday, December 31, 2016 8:30 AM
> Deborah Swanson writes:
>> > Is it possible to use some version of the "a = expression1 if 
> > condition else expression2" syntax with an elif? And for 
> expression1 
> > and expression2 to be single statements? That's the kind of 
> > shortcutting I'd like to do, and it seems like python might 
> be able to 
> > do something like this.
>> I missed this question when I read the thread earlier. The 
> answer is simply to make expression2 be another conditional 
> expression. I tend to write the whole chain in parentheses. 
> This allows multi-line layouts like the following alternatives:
>> a = ( first if len(first) > 0
> else second if len(second) > 0
> else make_stuff_up() )
>> a = ( first if len(first) > 0 else
> second if len(second) > 0 else
> make_stuff_up() )
>> Expression1 and expression2 cannot be statements. Python 
> makes a formal distinction between statements that have an 
> effect and expressions that have a value. All components of a 
> conditional expression must be expressions. A function call 
> can behave either way but I think it good style that the 
> calls in expresions return values.

While I'm sure these terniaries will be useful for future problems, I
couldn't make the second one work for my current problem. I got as far
as:
a = l1[v] if len(l1[v] > 0 else 
 l2[v] if len(l2[v] > 0 else
And didn't finish it because I couldn't see what a should be. I want it
to be 
l2[v] if the first clause is true, and l1[v] if the second. If I was
computing a value, this would work beautifully, but I don't see how it
can if I'm choosing a list element to assign to. Maybe I just can't see
it.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /