【问题标题】:increment int within an inline if in python [duplicate]如果在python中,则在内联中增加int [重复]
【发布时间】:2021-02-05 11:09:43
【问题描述】:

我有一个以None 开头的值,但应该成为int,并在循环中递增。我尝试使用内联 if 来检查它是否为 None ,否则增加。但是内联 if 语句抛出:

x = None
for _ in range(5):
    if x is None:
        x = 1
    else:
        x +=1
print(x)

x= None
for _ in range(5):
    x = 1 if x is None else +=1 #SyntaxError: invalid syntax
    x +=1 if x is not None else 1 #TypeError unsupported operand type(s) for +=: 'NoneType' and 'int'
print(x)

如果您不明确使用 += 和 operator 和 x,它会起作用:x = 1 if x is None else x+1。但我在徘徊是否或如何在内联 if 中使用+=

【问题讨论】:

  • 所谓的“inline if”是一个条件表达式+= 语句不是表达式。
  • 那为什么不以x = 0开头呢?
  • @UnholySheep x 是来自第三方模块的对象的属性。
  • @ChristopherPeisert 确实如此!但我还需要它不是实际的“内联 if”的信息。

标签: python conditional-operator


【解决方案1】:

您在x = 1 if x is None else x+1 中正确使用内联代码,您不能在内联中使用+=。 为了理解,让我们在不影响代码的情况下添加一些括号:

x = None
for _ in range(5):
    x = (1 if x is None else x+1)
    # same as
    if x is None:
        x = 1
    else:
        x = x + 1

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2014-03-17
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多