python - How do I test one variable against multiple values? -


i'm trying make function compare multiple variables integer , output string of 3 letters. wondering if there way translate python. say:

x = 0 y = 1 z = 3 mylist = []  if x or y or z == 0 :     mylist.append("c") elif x or y or z == 1 :     mylist.append("d") elif x or y or z == 2 :     mylist.append("e") elif x or y or z == 3 :      mylist.append("f") 

which return list of

["c", "d", "f"] 

is possible?

you misunderstand how boolean expressions work; don't work english sentence , guess talking same comparison names here. looking for:

if x == 1 or y == 1 or z == 1: 

x , y otherwise evaluated on own (false if 0, true otherwise).

you can shorten to:

if 1 in (x, y, z): 

or better still:

if 1 in {x, y, z}: 

using set take advantage of constant-cost membership test (in takes fixed amount of time whatever left-hand operand is).

when use or, python sees each side of operator separate expressions. expression x or y == 1 treated first boolean test x, if false, expression y == 1 tested.

this due operator precedence. or operator has lower precedence == test, latter evaluated first.

however, if not case, , expression x or y or z == 1 interpreted (x or y or z) == 1 instead, still not expect do.

x or y or z evaluate first argument 'truthy', e.g. not false, numeric 0 or empty (see boolean expressions details on python considers false in boolean context).

so values x = 2; y = 1; z = 0, x or y or z resolve 2, because first true-like value in arguments. 2 == 1 false, though y == 1 true.

the same apply inverse; testing multiple values against single variable; x == 1 or 2 or 3 fail same reasons. use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -