vendredi 20 octobre 2017

Is there a way to combine memberwise comparison within an if-statement in python?

I want to check multiple conditions in an if-statement

if a:
    do something

a in this case is true for multiple cases a==1, a==2, a==3

instead of writing

if a == 1 or a == 2 or a ==3:
    do something

I am trying something like this

if a == condition for condition in [1, 2, 3]:
    do something

I get the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


EDIT: I had a different Problem underlying but the following answers the question

if a in {1, 2, 3}:
    #do something

Aucun commentaire:

Enregistrer un commentaire