【问题标题】:Python: Initialize variable in expression of if condition [duplicate]Python:在if条件表达式中初始化变量[重复]
【发布时间】:2022-02-03 06:39:59
【问题描述】:

在下面的代码中,我计算 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

【问题讨论】:

  • 简短回答:对于 Python >= 3.8,使用 j := nums.index(...) 而不是 j = nums.index(...)。对于较早的 Python 版本,请在 if 行之前初始化 j(在我看来,这无论如何都更具可读性)。

标签: python


【解决方案1】:

是的,您可以使用 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2019-09-30
    • 1970-01-01
    相关资源
    最近更新 更多