I have a one liner if
statement that looks like this:
var = var if var < 1. else 1.
The first part var = var
looks a bit ugly and I'd bet there's a more pythonic way to say this.
I have a one liner if
statement that looks like this:
var = var if var < 1. else 1.
The first part var = var
looks a bit ugly and I'd bet there's a more pythonic way to say this.
The following is 39% shorter and in my opinion is simpler and more pythonic than other answers. But we should note that sometimes people get it wrong thinking that 1 is a lower bound being confused by min
function when actually 1 is an upper bound for var
.
var = min(var, 1.0)
if var >= 1.:
var = 1
or if you like one liners
if var >= 1.: var = 1
Doesn't eliminate the var = var
but it's shorter and one could argue, more pythonic:
var = min(var, 1.0)
You can use the equivalence of True=1 and False=0 to index into a 2-tuple of the possible values:
var = (1,var)[var < 1.]
If var < 1.
, then this evalutes to True, which is equivalent to 1. This simplifies to:
var = (1,var)[1]
Or
var = var
if not var < 1.
, this evaluates to False, which is equivalent to 0, giving:
var = (1,var)[0]
or
var = 1
So this one-liner:
var = (1,var)[var < 1.]
is equivalent to:
if var < 1.:
var = var
else:
var = 1