有没有正确的方法在 1 个 if 语句中有两个海象运算符?
if (three:= i%3==0) and (five:= i%5 ==0):
arr.append("FizzBuzz")
elif three:
arr.append("Fizz")
elif five:
arr.append("Buzz")
else:
arr.append(str(i-1))
此示例适用于three
但five
将“未定义”。
有没有正确的方法在 1 个 if 语句中有两个海象运算符?
if (three:= i%3==0) and (five:= i%5 ==0):
arr.append("FizzBuzz")
elif three:
arr.append("Fizz")
elif five:
arr.append("Buzz")
else:
arr.append(str(i-1))
此示例适用于three
但five
将“未定义”。
逻辑运算and
符仅有条件地评估其第二个操作数。没有正确的方法来进行无条件需要的条件赋值。
而是使用“二元”运算符&
,它无条件地计算其第二个操作数。
arr = []
for i in range(1, 25):
# v force evaluation of both operands
if (three := i % 3 == 0) & (five := i % 5 == 0):
arr.append("FizzBuzz")
elif three:
arr.append("Fizz")
elif five:
arr.append("Buzz")
else:
arr.append(str(i))
print(arr)
# ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', ...]
相应地,可以|
用作 的无条件变体or
。此外,“xor”运算符^
根本没有条件评估的等价物。
值得注意的是,二元运算符将布尔值评估为纯布尔值 - 例如,False | True
不是- 但对于其他类型可能会有所不同。要使用二元运算符在布尔上下文中评估任意值(例如s),请将它们转换为赋值后:True
1
list
bool
# |~~~ force list to boolean ~~| | force evaluation of both operands
# v v~ walrus-assign list ~vv v
if bool(lines := list(some_file)) & ((today := datetime.today()) == 0):
...
由于赋值表达式需要括号来获得适当的优先级,因此逻辑 ( , ) 和二进制 ( , , ) 运算符之间优先级不同的常见问题在这里无关紧要。and
or
&
|
^
您遇到的问题是,由于短路,仅在此语句中为 Truefive
时才分配:three
if (three:= i%3==0) and (five:= i%5 ==0)
所以five
通常不会分配导致 aNameError
或使用非当前值。
您可以通过在其中形成一个带有海象赋值的非空元组然后在该元组之后使用three
和five
您期望的那样来强制一个 True 值。
它并不比分配three
和five
之前更漂亮,if
但这有效:
arr=[]
for i in range(1,26):
if (three:=i%3==0, five:=i%5==0) and three and five:
arr.append(f"{i} FizzBuzz")
elif three:
arr.append(f"{i} Fizz")
elif five:
arr.append(f"{i} Buzz")
else:
arr.append(f"{i}")
>>> arr
['1', '2', '3 Fizz', '4', '5 Buzz', '6 Fizz', '7', '8', '9 Fizz', '10 Buzz', '11', '12 Fizz', '13', '14', '15 FizzBuzz', '16', '17', '18 Fizz', '19', '20 Buzz', '21 Fizz', '22', '23', '24 Fizz', '25 Buzz']
任何非空元组都True
在 Python 中。形成它会导致(three:=i%3==0, five:=i%5==0)
永远是真实的,并且每次分配三个和五个。由于该元组为真,因此必须使用正确的值 3 和 5 来评估表达式的其余部分。
或者,使用if all((three:=i%3==0, five:=i%5==0)):
因为元组是在测试其内容之前形成的——即使所有短路;这只会在元组形成后发生。
这些形式中的任何一种都可以轻松重构为理解:
arr=[f"{i} FizzBuzz" if three and five
else f"{i} Fizz" if three
else f"{i} Buzz" if five
else f"{i}"
for i in range(1,26) if (three:=i%3==0, five:=i%5==0)]
或者,
arr=[f"{i} FizzBuzz" if all((three:=i%3==0, five:=i%5==0))
else f"{i} Fizz" if three
else f"{i} Buzz" if five
else f"{i}" for i in range(1,26)]
if (three := i % 3 == 0) & (five := i % 5 == 0):
如果每个元素的结果不是布尔值,请注意构造。你可能会遇到一些意想不到的失败:
>>> bool((x:=3) & (y:=4))
False
>>> bool((x:=3) and (y:=4))
True
解决此问题的唯一方法已bool
应用于每个:
>>> bool(x:=3) & bool(y:=4)
True
顺便说一句,说到元组,在 Python 中进行 FizzBuzz 类型挑战的一种更短的方法:
fb={(True,True):"{} FizzBuzz",
(True,False):"{} Fizz",
(False,True):"{} Buzz",
(False,False):"{}"}
arr=[fb[(i%3==0,i%5==0)].format(i) for i in range(1,26)]
如果你正在寻找新的东西,这种类型的问题对于 Python 3.10+模式匹配来说是很自然的:
arr=[]
for i in range(1,26):
s=f"{i}"
match (i%3==0,i%5==0):
case (True, (True | False) as oth):
s+=" FizzBuzz" if oth else " Fizz"
case (False, True):
s+=" Buzz"
arr.append(s)