使用不熟悉的表达式类型理解此 Python“if 语句”
Understanding this Python ‘if statement’ with unfamiliar expression type
抱歉,如果这是一件简单的事情,我只是没有运气在网上得到答案(如果这不是 post 的好地方)。
我一直在努力改进我的 Python,并且我一直在努力理解神经 Network/Natural 语言处理包的一些代码。我遇到了这个:
if args.encoder_layers_to_keep:
args.encoder_layers = len(args.encoder_layers_to_keep.split(","))
我还没有遇到过带有这样表达式的 if 语句。变量或任何东西之间没有比较。我唯一的猜测是它 returns 是真值还是假值并且可以使用它,但我真的不确定。
作为参考,这里是完整的脚本 - https://github.com/pytorch/fairseq/blob/master/fairseq/models/transformer.py
如有任何帮助,我将不胜感激。
谢谢,
贾斯汀
空序列(例如,列表、元组、字符串)的计算结果为 False
。非空序列的计算结果为 True
.
args.encoder_layers_to_keep
好像是一个字符串变量。空字符串 ""
的计算结果为 False
,非空字符串的计算结果为 True
.
您可以通过使用内置函数 bool
转换为布尔值来向自己证明这一点。试试 bool("")
和 bool("foobar")
.
Python style guide (PEP8) 中建议:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
if not seq:
if seq:
# Wrong:
if len(seq):
if not len(seq):
抱歉,如果这是一件简单的事情,我只是没有运气在网上得到答案(如果这不是 post 的好地方)。
我一直在努力改进我的 Python,并且我一直在努力理解神经 Network/Natural 语言处理包的一些代码。我遇到了这个:
if args.encoder_layers_to_keep:
args.encoder_layers = len(args.encoder_layers_to_keep.split(","))
我还没有遇到过带有这样表达式的 if 语句。变量或任何东西之间没有比较。我唯一的猜测是它 returns 是真值还是假值并且可以使用它,但我真的不确定。
作为参考,这里是完整的脚本 - https://github.com/pytorch/fairseq/blob/master/fairseq/models/transformer.py
如有任何帮助,我将不胜感激。
谢谢, 贾斯汀
空序列(例如,列表、元组、字符串)的计算结果为 False
。非空序列的计算结果为 True
.
args.encoder_layers_to_keep
好像是一个字符串变量。空字符串 ""
的计算结果为 False
,非空字符串的计算结果为 True
.
您可以通过使用内置函数 bool
转换为布尔值来向自己证明这一点。试试 bool("")
和 bool("foobar")
.
Python style guide (PEP8) 中建议:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
if not seq: if seq: # Wrong: if len(seq): if not len(seq):