Jos*_*ady 6 python python-3.x walrus-operator
是否有在 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))
Run Code Online (Sandbox Code Playgroud)
该示例适用于three
但five
将“未定义”。
逻辑运算符and
仅有条件地计算其第二个操作数。没有正确的方法来进行无条件的条件赋值。
而是使用“二元”运算符&
,它无条件地计算第二个操作数。
arr = []\nfor i in range(1, 25):\n # v force evaluation of both operands\n if (three := i % 3 == 0) & (five := i % 5 == 0):\n arr.append("FizzBuzz")\n elif three:\n arr.append("Fizz")\n elif five:\n arr.append("Buzz")\n else:\n arr.append(str(i))\n\nprint(arr)\n# [\'1\', \'2\', \'Fizz\', \'4\', \'Buzz\', \'Fizz\', \'7\', \'8\', \'Fizz\', \'Buzz\', \'11\', ...]\n
Run Code Online (Sandbox Code Playgroud)\n相应地,我们可以将其用作 的|
无条件变体or
。此外,“异或”运算符^
根本没有条件求值的等价物。
值得注意的是,二元运算符将布尔值评估为纯布尔值 - 例如,False | True
不是\xe2\x80\x93,但对于其他类型可能会有所不同。要使用二元运算符在布尔上下文中计算任意值(例如s),请将它们转换为True
1
list
bool
s),请将它们转换为赋值后的值:
# |~~~ force list to boolean ~~| | force evaluation of both operands\n# v v~ walrus-assign list ~vv v\nif bool(lines := list(some_file)) & ((today := datetime.today()) == 0):\n ...\n
Run Code Online (Sandbox Code Playgroud)\n由于赋值表达式需要括号来保证正确的优先级,因此逻辑 ( , ) 和二元 ( , , ) 运算符之间优先级不同的常见问题在这里无关紧要。and
or
&
|
^