除了下面的蠻力方法,是否有一個更簡單的方法來分配值給變量給定條件?有沒有一種更簡單的方法來分配值給一個變量如果條件 - Python?
方法1:
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
除了下面的蠻力方法,是否有一個更簡單的方法來分配值給變量給定條件?有沒有一種更簡單的方法來分配值給一個變量如果條件 - Python?
方法1:
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)
,但如果你有很多的變量,以完全相同的方式被處理list
可能會更好。
values = [0.03,0.4,0.055,0.7]
x = 0.2
values = [max(v, x) for v in 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
絕對考慮使用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)
也許,更多的哈斯克爾樣(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)))
一些基本timeint(達爾文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(值)比max(* values)更快?
你的代碼看起來很奇怪。它可能包含錯誤。你想做什麼? –