2013-01-07 101 views

回答

20

也許:

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] 
-3

嘗試:

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 
+5

SyntaxError。 Python不是Perl。 – ThiefMaster

+0

糾正它們! –

+1

爲什麼會出現虛假的括號? Python不是C. – Duncan

2

絕對考慮使用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) 
0

也許,更多的哈斯克爾樣(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)更快?

相關問題