2013-01-07 62 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)更快?

相关问题