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
都是没有长度或布尔值的自定义类实例(如Node()
或类似),则只需使用:如果以太
head
或tail
可以是None
以外的具有false-y值(False
、数字0、空容器等)的对象,则这将不起作用。在否则,您就只能使用显式测试。布尔逻辑中没有“英语语法”的捷径。在
清晰有效。如果}在它们都是{}时打印出来,那么您所写的比
^{pr2}$head
或tail
可能会在None
之外获取虚假的ish值,但您只希望{一个更紧凑的版本(比您的代码)既安全又高效
head is None is tail
实际上相当于(head is None) and (None is tail)
。但我觉得它比你原来的版本可读性差一点。在顺便说一句,
(head and tail) is None
是有效的Python语法,但不建议这样做,因为它并不像您最初预期的那样:输出
你的代码就像Python一样。在
当谈到这些事情时,The Zen of Python是有帮助的,记住有时候直截了当是最好的选择。在
相关问题 更多 >
编程相关推荐