在Python中是否有特纳利条件操作器?


当前回答

a if condition else b

记住这个金字塔,如果你有记住问题:

     condition
  if           else
a                   b 

其他回答

模拟 Python Ternary 操作器。

例如

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()

出口:

'b greater than a'

<表达 1> 如果 <条件> 其他 <表达 2>

a = 1
b = 2

1 if a > b else -1 
# Output is -1

1 if a > b else -1 if a < b else 0
# Output is -1

连接多个运营商的方式:

f = lambda x,y: 'greater' if x > y else 'less' if y > x else 'equal'

array = [(0,0),(0,1),(1,0),(1,1)]

for a in array:
  x, y = a[0], a[1]
  print(f(x,y))

# Output is:
#   equal,
#   less,
#   greater,
#   equal

我发现默认的Python合成val = a if cond other b cumbersome,所以有时我这样做:

iif = lambda (cond, a, b): a if cond else b
# So I can then use it like:
val = iif(cond, a, b)

当然,它有一个缺点,总是评估双方(a和b),但合成对我来说更清楚。

在 2.5 之前的版本中,有以下技巧:

[expression] and [on_true] or [on_false]

它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。

雖然它有評估表達的好處留在右邊,這在我看來更清楚。

是否有“C”的“?”:“特纳利运营商的同等值?