Python Shorthand if - 0 在计算结果中解释为false

Python Shorthand If - 0 interpreted as false in calculation result

for i in range(0,len(A) - 1): 
   cand = (A[i] + A[i + 1]) / 2
   cand2 = i + 2 < len(A) and (A[i] + A[i + 1] + A[i + 2]) / 3 or cand
   A[i] = min(cand, cand2)

我编写了上面的代码来计算整数数组接下来的两个和三个元素的最小平均值。例如,如果我们有数组 [2,3,5,6],在第一次迭代中 cand 将是 2.5cand2 将是 3.33,因此 A[0] 将更新为2.5等。

此代码有效,但 (A[i] + A[i + 1] + A[i + 2]) / 30 时除外。在这种情况下,or 语句执行并且 cand2 被设置为 cand.

我很确定这是因为 Python 将 0 解释为 False 并执行 or 语句 - 我该如何解决这个问题?

看来你想在这里做一个三元组,它会像这样工作:

for i in range(0,len(A) - 1): 
   cand = (A[i] + A[i + 1]) / 2
   cand2 = (A[i] + A[i + 1] + A[i + 2]) / 3 if i + 2 < len(A) else cand
   A[i] = min(cand, cand2)

你用布尔运算符链接它们,这可能会起作用,因为在 python 它们做了一些技巧(and 链接的表达式将 return 的第一个 Falsy 值chain, or the last value if all are Truthy - - - or-chained expression 将 return 第一个 Truthy 值或 value if all are Falsy),但这会使你的程序更难明白了。

无论如何,您可能需要考虑在此处使用常规 if 结构以获得最佳可读性。

Some unspoken rules are:

  • The if branch should be the most likely one.
  • Don’t use nested ternary operators (use plain multi-line if ... elif > ... then ... statements instead).
  • Don’t use long ternary operators with complicated expressions (again use multi-line if statements instead).
for i in range(0,len(A) - 1): 
    cand = (A[i] + A[i + 1]) / 2
    if i + 2 < len(A):
        cand2 = (A[i] + A[i + 1] + A[i + 2]) / 3
    else:
        cand2 = cand
    A[i] = min(cand, cand2)