python - 列表评估为 bool 值但作为列表返回

标签 python

我是 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 x

This 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/

相关文章:

python - 如何以随机顺序循环遍历 Python 字典的项目?

Python 方法访问器在每次访问时创建新对象?

python - 如何*不*在 ipython 笔记本(pandas 数据帧的 html 表)中显示 'NaN'?

python - 了解 Python 中嵌套函数中的变量作用域

python - 如何将装饰器应用于 Cython cpdef 函数

python - 打印最大值和数据

python - add2virtualenv(virtualenv 包装器)不适用于 scipy

python - 替换 Python 中以反斜杠开头的单词

python - numpy 从二维矩阵获取子矩阵

python - 与 python 对象相关的值是什么意思?