Python:初始化if条件表达式中的变量



在下面的代码中,我计算了两次nums.index((。

if ((elem in nums) and i != nums.index(elem)):
j = nums.index(elem)
return i,j

有没有一种方法可以初始化表达式本身中的变量,并在if条件的作用域中使用它?也许像这个

if ((elem in nums) and i != (j = nums.index(elem))):
return i,j

是的,您可以使用The Walrus Operator :=

elem = 10
nums = [11, 2, 10, 2, 3]

def fun():
i = 3
if (elem in nums) and i != (j := nums.index(elem)):
return i, j

fun()

最新更新