首页 > 解决方案 > Python3的map函数中排除空值

问题描述

map用来处理 Python3.6 中的列表:

def calc(num):
    if num > 5:
        return None
    return num * 2


r = map(lambda num: clac(num), range(1, 10))
print(list(r))

# => [2, 4, 6, 8, 10, None, None, None, None]

我期望的结果是:[2, 4, 6, 8, 10].

当然,我可以用它filter来处理map结果。但是有没有办法map直接返回我想要的结果?

标签: pythonpython-3.xmap-function

解决方案


map不能直接过滤掉项目。它为每个输入项输出一项。您可以使用列表理解None从结果中过滤掉。

r = [x for x in map(calc, range(1,10)) if x is not None]

(这只calc对范围内的每个数字调用一次。)

旁白:没有必要写lambda num: calc(num). 如果你想要一个返回结果的函数calc,只需使用calc它自己。


推荐阅读