python - What would be a compact way to return 1 if a variable is 0 and to return 0 if it is 1? -
how following made more compact (perhaps using booleans), given supplied integer variable?
indextag = 0 # or 1 1 if indextag == 0 else 0
you use not
:
not indextag
which gives boolean (true
or false
), python booleans subclass of int
, have integer value (false
0
, true
1
). turn integer int(not indextag)
if boolean, why bother?
or subtract 1; 1 - 0
1
, , 1 - 1
0
:
1 - indextag
or use conditional expression:
0 if indextag else 1
demo:
>>> indextag in (0, 1): ... print 'indextag:', indextag ... print 'boolean not:', not indextag ... print 'subtraction:', 1 - indextag ... print 'conditional expression:', 0 if indextag else 1 ... print ... indextag: 0 boolean not: true subtraction: 1 conditional expression: 1 indextag: 1 boolean not: false subtraction: 0 conditional expression: 0
Comments
Post a Comment