Cleaning up conditionals
python at deborahswanson.net
Fri Dec 30 18:17:55 EST 2016
> On Fri, 30 Dec 2016 13:20:15 -0800, "Deborah Swanson"
> <python at deborahswanson.net> declaimed the following:
> >I've already learned one neat trick to collapse a conditional:
> > a = expression1 if condition else expression2
> >Here I have a real mess, in my opinion:
> > if len(l1[st]) == 0:
> > if len(l2[st]) > 0:
> > l1[st] = l2[st]
> > elif len(l2[st]) == 0:
> > if len(l1[st]) > 0:
> You will never reach here. The above "elif" is only
> reachable if "len(l1[st])" IS EQUAL TO 0, which means that
> the later "if" can not be true.
> > l2[st] = l1[st]
> > (Basically, if one field from two adjacent rows is empty and the
> >other is
> > not, copy the non-empty field to the empty one. I use this
> for rental
> > listings that are identical but posted on different dates,
> to copy the
> > data from an older one to the new one. Or, if I look up
> the data for
> >a new
> > listing, to copy it back to the older ones.)
> >Anybody know or see an easier (more pythonic) way to do
> this? I need to
> >do it for four fields, and needless to say, that's a really
> long block
> >of ugly code.
> Ever consider using conjunctions?
> if len(l1[st]) and not len(l2[st]):
> #0 is considered a false -- no need to test for "==0"
> #non-0 is considered true -- no need to test for ">0"
> #copy l1 to l2
> elif not len(l1[st]) and len(l2[st]):
> #copy l2 to l1
> Wulfraed Dennis Lee Bieber AF6VN
> wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/
That's a neat shortcut, len(a) instead of len(a)!= 0. Thanks!
Yes, 4 lines is an improvement on 6 lines, but I was hoping for
something more radical.
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
More information about the Python-list