Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude null values in map function of Python3

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?

like image 405
Martin Zhu Avatar asked Jul 05 '18 11:07

Martin Zhu


1 Answers

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.

like image 196
khelwood Avatar answered Oct 04 '22 00:10

khelwood