J'ai une variable que je veux régler selon les valeurs de trois booléens. La plus straight-forward est un si la déclaration suivie par une série de elifs:
if a and b and c:
name = 'first'
elif a and b and not c:
name = 'second'
elif a and not b and c:
name = 'third'
elif a and not b and not c:
name = 'fourth'
elif not a and b and c:
name = 'fifth'
elif not a and b and not c:
name = 'sixth'
elif not a and not b and c:
name = 'seventh'
elif not a and not b and not c:
name = 'eighth'
C'est un peu maladroit, et je me demandais si il n'y a plus Pythonic façon de traiter ce problème. Quelques idées me viennent à l'esprit.
-
Dictionnaire hack:
name = {a and b and c: 'first', a and b and not c: 'second', a and not b and c: 'third', a and not b and not c: 'fourth', not a and b and c: 'fifth', not a and b and not c: 'sixth', not a and not b and c: 'seventh', not a and not b and not c: 'eighth'}[True]
J'appelle cela un hack parce que je ne suis pas trop sauvage sur sept des clés à Faux et en remplaçant les uns les autres.
-
Et/ou de la magie
name = (a and b and c and 'first' or a and b and not c and 'second' or a and not b and c and 'third' or a and not b and not c and 'fourth' or not a and b and c and 'fifth' or not a and b and not c and 'sixth' or not a and not b and c and 'seventh' or not a and not b and not c and 'eighth')
Cela fonctionne parce que Python ands et rup retourne la dernière valeur qui doit être évalué, mais vous devez savoir que pour comprendre ce bizarre code.
Aucune de ces trois options est très satisfaisant. Que recommandez-vous?