简化if语句python

2024-05-23 09:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有任何python或compact方法来编写以下if语句:

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

比如:

^{pr2}$

Tags: and方法testnoneifis语句head
3条回答

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

if not (head or tail):

如果以太headtail可以是None以外的具有false-y值(False、数字0、空容器等)的对象,则这将不起作用。在

否则,您就只能使用显式测试。布尔逻辑中没有“英语语法”的捷径。在

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

清晰有效。如果headtail可能会在None之外获取虚假的ish值,但您只希望{}在它们都是{}时打印出来,那么您所写的比

^{pr2}$

一个更紧凑的版本(比您的代码)既安全又高效

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有效的Python语法,但不建议这样做,因为它并不像您最初预期的那样:

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))

输出

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

你的代码就像Python一样。在

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

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

相关问题 更多 >

    热门问题