我是 python (3.6) 的新手,我写道:
def foo(alist, blist):
if alist or blist:
return alist or blist
print(foo([2], []))
打印[2]
。
我试图理解:似乎列表在 if alist or blist
中被评估为 False
\True
但在 return alist 或 blist
中,它返回列表本身而不是 False
\True
。怎么样?
alist 或 blist
计算结果是否为两者的非空列表?文档中的某处是否针对所有这些编写了任何规则?
谢谢
最佳答案
第一个列表 [2]
可以被认为是一个 True
值,与第二个空列表 []
相反,它是 False
在 bool 上下文中。
The following values are considered false: ....
any empty sequence, for example, '', (), [].
x or y
if x is false, then y, else xThis is a short-circuit operator, so it only evaluates the second argument if the first one is false
检查 docs
来自解释器:
>>> ['test'] or []
['test']
>>>
>>> ['test'] or ['test2']
['test']
>>>
>>> [] or ['test2']
['test2']
>>>
>>> [] or []
[]
关于python - 列表评估为 bool 值但作为列表返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42714606/