python - 使用 bool 表达式分配字符串

标签 python python-2.7

<分区>

我试图从其他人的项目中理解这段代码。如果你想要上下文,它就在这里:https://github.com/newsapps/beeswithmachineguns/blob/master/beeswithmachineguns/bees.py#L501

IS_PY2 只是一个 bool 变量,True 如果 Python 主要版本是 2。 我知道非空字符串是 True,但出于某种原因我不明白 openmode 被分配了 'w''wt' 而不是 TrueFalse

openmode = IS_PY2 and 'w' or 'wt'
openkwargs = IS_PY2 and {} or {'encoding': 'utf-8', 'newline': ''}

谁能解释一下结果?

最佳答案

andor 运算符 只是对其操作数执行 bool 运算,给出 bool 结果。他们给出的结果总是他们的操作数之一。这些运算符从左到右求值,and 的优先级高于 or,它们会短路,这意味着它们会尽快停止对操作数求值。

在纯 bool 逻辑中,False and xFalse,不管x是什么,所以不需要检查 x。 Python 表达式 False and x 将给出 False 的结果,并且不会尝试计算 x。因此 False 和 some_function()不会调用 some_function()

类似地,纯 bool 逻辑中的 True 和 x 将具有与 x 相同的真值,即,如果 x TrueTrue 且 xTrue,否则为 False

但是 Python 的 运算符可以处理任意操作数。

a 和 b 中,如果 a 是 false-ish,那么 b 将不会被计算,结果将是 一个。如果 a 为 true-ish,则 b 被评估并成为结果。

这是一个使用 Python 2 的简短演示:

print False and 'boolean'
print 0 and 'integer'
print '' and 'string'
print [] and 'list'
print

print True and 'boolean'
print 7 and 'integer'
print 'a' and 'string'
print [42] and 'list'
print

print True and False
print True and 0
print True and ''
print True and []
print

输出

False
0

[]

boolean
integer
string
list

False
0

[]

(0[] 之间的空行是打印空字符串的地方)。

类似的注意事项适用于 运算符。

在纯 bool 逻辑中,True 或 xTrue,无论 x 是什么,如果 的第一部分or 表达式是 True-ish 我们不需要评估第二部分。并且 False or x 的真值为 x

print False or 'boolean'
print 0 or 'integer'
print '' or 'string'
print [] or 'list'
print

print True or 'boolean'
print 7 or 'integer'
print 'a' or 'string'
print [42] or 'list'
print

print False or False
print False or 0
print False or ''
print False or []
print

输出

boolean
integer
string
list

True
7
a
[42]

False
0

[]

正如我之前所说,这些运算符是从左到右计算的,如果需要,我们可以将它们链接起来。以下是“经典”案例:

print True and 'yes' or 'no'
print False and 'yes' or 'no'

这些语句等同于

print (True and 'yes') or 'no'
print (False and 'yes') or 'no'

输出

yes
no

这种结构在 Python 的早期版本中很常见。如今,if 表达式变得更加常见:

print 'yes' if True else 'no'
print 'yes' if False else 'no'

这通常被认为比使用andor 的三元表达式更具可读性。此外,a and b or c not 等同于 b if a else c if b is false-ish .

但是,了解这个三元 and ... or 的工作原理仍然很重要,尤其是当您需要阅读或维护旧代码时。而一些老 Pythonista 仍然更喜欢 and ... 或 形式,因为它稍微短一些,即使当你不理解它是如何工作的时候它有点令人困惑。 :)

关于python - 使用 bool 表达式分配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36550588/

相关文章:

c - 如何将列表传递给 python 上的 ctypes 函数

python - 如何正确测试Django UpdateView?

具有多个标题行的 Python 网页抓取表

python - Cython编译错误: Python3 Compatibility

python - 为什么允许使用以下字符串文字?

python - Google App Engine - ConnectionError : ('Connection aborted.' , 错误 (13, 'Permission denied' ))

python - 如何将 Pandas 数据框的多行标题合并到单个单元格标题中?

python - 查找数据帧给定列中最高值的行索引

Python 重置列中间隔内的累积和

python - 如何在 Python 中读取键盘输入