I'm using try/except
blocks as a substitute for if/elif
that has a bunch of and
s. I am looking into a list and replacing some elements if it has x and x and x, etc. In my project, I have to check for upwards of 6 things which drew me to using the try/except
with .index
which will throw an error if the element isn't present.
An analogy looks like this:
colors = ['red', 'blue', 'yellow', 'orange']
try:
red_index = colors.index('red')
blue_index = colors.index('blue')
colors[red_index] = 'pink'
colors[blue_index] = 'light blue'
except ValueError:
pass
try:
yellow_index = colors.index('yellow')
purple_index = colors.index('purple')
colors[yellow_index] = 'amarillo'
colors[purple_index] = 'lavender'
except ValueError:
pass
So if the color array doesn't contain purple
as well as yellow
, I don't want the array to change.
I am a bit wary of this approach because it seems like abuse of try/except. But it is much shorter than the alternative because I would have to grab the elements' index
anyway, so I would like to know if there are blatant problems with this or if this is crazy enough that other developers would hate me for it.
Aucun commentaire:
Enregistrer un commentaire