Exclude null values in map function of Python3

蓝咒 提交于 2019-12-23 02:52:33

问题


I am using map to process a list in 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].

Of course, I can use filter to handle map result. But is there a way for map to return directly to the result I want?


回答1:


map cannot directly filter out items. It outputs one item for each item of input. You can use a list comphrehension to filter out None from your results.

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.)

Aside: there is no need to write lambda num: calc(num). If you want a function that returns the result of calc, just use calc itself.




回答2:


Not when using map itself, but you can change your map() call to:

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.



来源:https://stackoverflow.com/questions/51189698/exclude-null-values-in-map-function-of-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!