【问题标题】:Is there a simpler way to allocate value to a variable given a if condition - Python?有没有一种更简单的方法来为给定 if 条件的变量分配值 - Python?
【发布时间】:2012-12-21 04:56:02
【问题描述】:

除了下面的蛮力方法之外,有没有更简单的方法来给给定 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

【问题讨论】:

  • 您的代码看起来很奇怪。它可能包含错误。你想做什么?

标签: python if-statement variable-assignment


【解决方案1】:

也许:

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]

【讨论】:

    【解决方案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)
    

    【讨论】:

      【解决方案3】:

      也许,更像 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)))
      

      一些基本的timeits(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
      

      结论:

      • 元组的迭代速度比列表快?!?

      • starmap 胜过地图,尽管 max(values) 比 max(*values) 快 ?!?

      【讨论】:

        【解决方案4】:

        尝试:

        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
        

        【讨论】:

        • 语法错误。 Python 不是 Perl。
        • 为什么是假括号? Python 不是 C。
        • 这比原来的 IMO 更难阅读,而且要引导的字符更多。我想它节省了一些垂直空间。
        猜你喜欢
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多