I'm trying to create a script that uses the if/elif/else structure, but I'd like it to expand and contract the elifs with the number of elements in a list.
The attempt below contains 5 elements (a-e), and gets sorted through five conditionals (if, elif, elif, elif, else).
Is there an elegant way to make this script work if I were to input the set (a-z), without needing to make several more elif?
Values = (0.1,0.12,0.3,0.8,0.802)
Categories = ("a","b","c","d","e")
MySizeType = []
for i in Values:
if i < .2:
MySizeType.append(Categories[0])
elif i < .4:
MySizeType.append(Categories[1])
elif i < .6:
MySizeType.append(Categories[2])
elif i < .8:
MySizeType.append(Categories[3])
else:
MySizeType.append(Categories[4])
Expanding on my comment:
You can't dynamically build an if/elif structure, but you can accomplish the same logic with a loop and a dictionary that maps threshold values to categories. Something like this:
This will output...
...which appears correct for your sample data.
With a minor change to the data structures:
You could reduce that loop down to a single expression:
@KellyBundy points out that my initial statement was not entirely accurate. Here's a solution in the spirit of their comment that uses Jinja2 to dynamically generate a chain if
elsifstatements:The output is the same as the earlier code.
For the record, don't do this.