【问题标题】:Test a single variable multiple times in python in a single statement在单个语句中在 python 中多次测试单个变量
【发布时间】:2014-12-08 03:54:42
【问题描述】:

我在 uni 学习 Python,并被告知逻辑运算符和条件语句是如何工作的。我的问题是:有没有办法像这样压缩代码?

if (day != "Sunday" and day != "Saturday" and day != "Friday" and day != "Thursday" and day != "Wednesday" and day != "Tuesday" and day != "Monday"):
    print "That is not a day"
    return 0

任何建议都值得赞赏,我知道上面的例子很简单。

【问题讨论】:

    标签: python python-2.7 syntax conditional-statements logical-operators


    【解决方案1】:

    因为如果 day 是 "Monday" 那么 if 将不会被评估,并且足以跳过 if 中的所有其他条件导致它不被满足。这是因为short circuit evaluation

    当你写作时:

    if (not a) and (not b)
    

    这与 (De Morgan's laws) 相同:

    if not (a or b)
    

    这不是你的意思。

    【讨论】:

      【解决方案2】:

      您可以使用in 关键字。

      if day not in ("Sunday", "Saturday", "Friday", "Thursday", "Wednesday", "Tuesday", "Monday"):
      

      【讨论】:

      • 对于这种特殊情况,我们也可以这样做:import calendar; if day not in calendar.day_name: ....
      猜你喜欢
      • 2019-12-21
      • 1970-01-01
      • 2019-10-03
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多