除了以下蛮力方法之外,是否有更简单的方法可以在给定 if 条件的情况下将值分配给变量?
方法一:
a, b, c, d = 0.03,0.4,0.055,0.7
x = 0.2
if a < x:
a = x
if b < x:
b = x
if c < x:
c = x
if d < x:
d = x
除了以下蛮力方法之外,是否有更简单的方法可以在给定 if 条件的情况下将值分配给变量?
方法一:
a, b, c, d = 0.03,0.4,0.055,0.7
x = 0.2
if a < x:
a = x
if b < x:
b = x
if c < x:
c = x
if d < x:
d = x
也许:
a, b, c, d = max(a, x), max(b, x), max(c, x), max(d, x)
但是如果你有很多变量以完全相同的方式处理,alist
可能会更好。
values = [0.03,0.4,0.055,0.7]
x = 0.2
values = [max(v, x) for v in values]
绝对考虑使用numpy.where
哪个是最有效的方法来处理任何大小的数组和维度:
#your example:
a,b,c,d = 0.03,0.4,0.055,0.7
x = 0.2
#solution
values = numpy.asarray([a, b, c, d])
a,b,c,d = numpy.where(values<x, x, values)
#efficiency becomes clear when
values = numpy.random.rand(1000,100,10) #any size and number of dimensions
values = numpy.where(values<x, x, values) #just works fine and efficient
#further developments would be possible, e.g., multiple conditions
values = numpy.where((values>=0.3)&(values<0.7), 0.5, values)
也许,更像 Haskell(zipWith)
from itertools import izip, starmap, repeat
a, b, c, d = starmap(max, izip(repeat(0.2), (0.03, 0.4, 0.055, 0.7)))
一些基本时间(darwin 12.2.0,py 2.7.3):
In [0]: %timeit a,b,c,d = starmap(max, izip(repeat(0.2), (0.03, 0.4, 0.055, 0.7)))
1000000 loops, best of 3: 1.87 us per loop
In [1]: %timeit a,b,c,d = map(max, izip(repeat(0.2), (0.03, 0.4, 0.055, 0.7)))
100000 loops, best of 3: 3.99 us per loop
In [2]: %timeit a,b,c,d = [max(0.2, v) for v in [0.03,0.4,0.055,0.7]]
100000 loops, best of 3: 1.95 us per loop
In [3]: %timeit a,b,c,d = [max(0.2, v) for v in (0.03,0.4,0.055,0.7)]
1000000 loops, best of 3: 1.62 us per loop
结论:
元组的迭代速度比列表快?!?
星图胜过地图,即使 max(values) 比 max(*values) 快?!?
尝试:
a = x if a < x else a
b = x if b < x else b
c = x if c < x else c
d = x if d < x else d