使用reduce mul在空白列表中返回1而不是None

0 python reduce list

当我通过一个空列表时,我试图返回1而不是None reduce(mul, a).我的代码:

from operator import mul
def product_list(a):
    for b in a:
        b = reduce(mul, a)
        if b == None:
            return 1
        return b

print product_list([])
Run Code Online (Sandbox Code Playgroud)

无论我在哪里放置if语句来捕获空白列表,我仍然会收到None作为输出.我还在学习基础知识,但这对我来说毫无意义.我甚至试过了

from operator import mul
def product_list(a):
    if a == None:
        return 1
    else:
        for b in a:
            b = reduce(mul, a)
            if b == None or a == None:
                return 1
            return b

print product_list([])
Run Code Online (Sandbox Code Playgroud)

只是为了看看它是否会捕获None并返回1. reduce()不按我认为的方式行事,或者我的代码中是否存在明显的错误,禁止返回1并强制返回None?

Mar*_*ers 6

如果a是空列表,则函数不返回任何内容,并且默认返回值为None.

测试顶部的空列表:

if not a:
    return 1
Run Code Online (Sandbox Code Playgroud)

在您的第二个函数中,您只测试if a == None,但空列表[]永远不会等于None.请注意,测试的惯用方法None是使用is对象标识测试:

if a is None:
Run Code Online (Sandbox Code Playgroud)

通过测试not a,您可以捕获a空列表存在的情况None.

你的代码没有多大意义.你循环a但在第一次迭代中返回并退出函数:

for b in a:
    b = reduce(mul, a)
    if b == None:
        return 1
    return b  # exit the function here, having only looked at the first element in `a`.
Run Code Online (Sandbox Code Playgroud)

但是,我必须在你的帖子中修改缩进,并且可能误解了这些return语句的缩进,在这种情况下,NameError当传入一个空列表时,你会得到一个.