列表计算为布尔值但返回列表

时间:2017-03-10 09:20:51

标签: python

我是python(3.6)的新手,我写道:

def foo(alist, blist):
    if alist or blist:
        return alist or blist

print(foo([2], []))

打印[2]

我正在努力理解:似乎列表会在False中评估为True \ if alist or blist,但在return alist or blist中会返回列表本身而不是False \ True。怎么样?

alist or blist是否评估两者的非空列表?是否有任何规则写在文档的某处?

由于

2 个答案:

答案 0 :(得分:3)

第一个列表[2]可以被视为True值,与第二个空列表[]相对,布尔中的False上下文。

  

以下值被视为 false :   ....

     

任何空序列,例如'',(), []

  

x or y如果x为false,则为y, else x

     

这是一个短路运算符,所以它只评估第二个参数,如果第一个参数是假的

检查docs

来自解释器

>>> ['test'] or []
['test']
>>>
>>> ['test'] or ['test2']
['test']
>>>
>>> [] or ['test2']
['test2']
>>>
>>> [] or []
[]

答案 1 :(得分:1)

检查代码注释以理解代码:

def foo(alist, blist):
    if alist or blist:

        #this if condition checks if alist is empty or blist is empty
        # Means: in actual this condition will be like this
        if alist != None or blist != None
        #None means if the list is empty or not

       return alist or blist

       # it returns the non-empty list just like the above explanation 
       # If both lists have some values then it will always return the first list which is alist

print(foo([2], []))
# Try you code with following statements to understand it

print(foo([], []))
# You will get None

print(foo([2], [3]))
# You will get [2]

print(foo([2], [2,4,5]))
# You will get [2]

print(foo([], [3]))
# You will get [3]