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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With