简化if语句python

时间:2016-12-02 13:41:11

标签: python python-3.x if-statement

是否有任何Pythonic或compact方式来编写以下if语句:

if head is None and tail is None:
    print("Test")

类似的东西:

if (head and tail) is None: 

4 个答案:

答案 0 :(得分:4)

如果headtail都是自定义类实例(如Node()或类似),没有长度或布尔值,那么只需使用:

if not (head or tail):

如果以太headtail可能是除None以外的对象且false-y值(False,数字0,空容器,则无效等)。

否则,您将坚持使用显式测试。布尔逻辑中没有“英语语法”快捷方式。

答案 1 :(得分:2)

if head is None and tail is None:
    print("Test")

清晰有效。如果headtail可能会在None之外采用虚假值,但您只需要"Test"打印None if not (head or tail): print("Test") 然后你写的比

更安全
if head is None is tail:
    print("Test")

更紧凑的版本(比您的代码)仍然是安全的和高效是

head is None is tail

(head is None) and (None is tail)实际上相当于(head and tail) is None。但我认为它的可读性比原始版本差一点。

顺便说一句,from itertools import product print('head, tail, head and tail, result') for head, tail in product((None, 0, 1), repeat=2): a = head and tail print('{!s:>4} {!s:>4} {!s:>4} {!s:>5}'.format(head, tail, a, a is None)) 有效的Python语法,但不建议这样做,因为它没有做你最初期望的那样:

head, tail, head and tail, result
None None None  True
None    0 None  True
None    1 None  True
   0 None    0 False
   0    0    0 False
   0    1    0 False
   1 None None  True
   1    0    0 False
   1    1    1 False

<强>输出

Instant instant = Instant.parse("2016-03-23T17:14:00.092812Z");
LocalTime newTime = LocalTime.parse("12:34:45.567891");
ZonedDateTime dt = instant.atZone(ZoneOffset.UTC);
dt = dt.with(newTime);
instant = dt.toInstant();
System.out.println("instant = " + instant);
// prints 2016-03-23T12:34:45.567891Z

答案 2 :(得分:1)

你的代码就像Pythonic一样。

说到这些事情,The Zen of Python有助于记住有时候直截了当是最好的选择。

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
etc...

答案 3 :(得分:0)

顺便说一下,编程中不允许像(head and tail) is None这样的描述,原因与数学中不允许(a and b) = 0相同的原因(强制每个语句只有一个规范形式;&#34 ;应该有一种明显的方法来做每一件事#34;也是一个explicit Python的座右铭。)

相关问题