【问题标题】:how to use ternary operator to write this if statement [closed]如何使用三元运算符编写此 if 语句 [关闭]
【发布时间】:2016-05-05 12:19:25
【问题描述】:
def get(count=None): 
    if count >= 1: 
        a = count - 1
    else: 
        a = 0
    return a

一切都在标题中。只是为了运动。

谢谢

【问题讨论】:

  • 什么是replies
  • 此代码在 Python 3.x 中有时会失败。
  • @ignacio 这是 2.7 的问题,但为什么在 python 3 中?
  • 因为您会将Noneint 进行比较。
  • 这不是 Stack Overflow 的好问题,请尝试codegolf.stackexchange.com

标签: python if-statement pep


【解决方案1】:

您的意思是使用ternary operator

a = count - 1 if count >= 1 else 0

如果countNone,您的代码将失败,因为您无法将非类型与整数进行比较。但我的回答是,如何以“更好”的方式编写这个条件语句。


因此 - 我会这样编写函数(感谢 @poke max 的想法。):

def get(count=None):
    return max(count-1, 0) if isinstance(count, int) else 0

【讨论】:

  • 没错,谢谢!我以前试过,但只能返回一个布尔值。
猜你喜欢
  • 2021-09-15
  • 1970-01-01
  • 2021-02-13
  • 2021-09-10
  • 2018-04-18
  • 2013-07-01
  • 2021-03-04
  • 1970-01-01
  • 2010-12-03
相关资源
最近更新 更多