How can I simplify this complex logical condition?
For a much shorter and more readable code
if i < 13:
linux0[j] = query_res
elif 13 <= i < 27:
linux1[j] = query_res
elif 27 <= i < 28:
linux2[j] = query_res
elif 28 <= i < 33:
linuxDnsServer1[j] = query_res
elif 33 <= i < 41:
linuxRadius[j] = query_res
elif 41 <= i < 46:
gen[j] = query_res
elif 46 <= i < 49:
cdu[j] = query_res
elif 49 <= i < 55:
avalanche[j] = query_res
elif 55 <= i < 69:
defensePro_devices[j] = query_res
Kyle Parsons
1,5559 silver badges14 bronze badges
1 Answer 1
It's not clear that it's more understandable, but you can put the limits and lists in another list, and iterate over it;
targets = [(12, linux0), (26, linux1), (27, linux2), (32, linuxDnsServer1),
(40, linuxRadius), (45, gen), (48, cdu), (54, avalanche), (68, defensePro_devices)]
for limit, target in targets:
if i <= limit:
target[j] = query_res
break
answered Aug 4, 2021 at 19:50
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Brian61354270
To add: 1) If you need non-consecutive intervals, you can swap the limits with explicit
range objects and then use if i in interval in place of if i <= limit. 2) You can also add an else branch at the end of the for to handle the case where no match is found (i.e. when the break statement is never reached)Barmar
I was going to put #2 in, but since the original code doesn't print an error, I left it out.
Barmar
Another way to handle non-consecutive intervals is to use an extra list for the gaps.
lang-py