简体   繁体   English

在Python3的map函数中排除空值

[英]Exclude null values in map function of Python3

I am using map to process a list in Python3.6:我正在使用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]

The result I expect is: [2, 4, 6, 8, 10] .我期望的结果是: [2, 4, 6, 8, 10]

Of course, I can use filter to handle map result.当然,我可以使用filter来处理map结果。 But is there a way for map to return directly to the result I want?但是有没有办法让map直接返回我想要的结果?

map cannot directly filter out items. map不能直接过滤项目。 It outputs one item for each item of input.它为每一项输入输出一项。 You can use a list comphrehension to filter out None from your results.您可以使用列表理解从结果中过滤掉None

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

(This only calls calc once on each number in the range.) (这只会对范围内的每个数字调用一次calc 。)

Aside: there is no need to write lambda num: calc(num) .旁白:没有必要写lambda num: calc(num) If you want a function that returns the result of calc , just use calc itself.如果您想要一个返回calc结果的函数,只需使用calc本身。

Not when using map itself, but you can change your map() call to:不是在使用map本身时,但您可以将map()调用更改为:

r = [calc(num) for num in range(1, 10) if calc(num) is not None]
print(r)  # no need to wrap in list() anymore

to get the result you want.得到你想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM