+ 1
Can I use the map funtcion with range in a for loop in python
i might just being using a super flous function to accomplish this but anyone know a way i can get this to work? https://code.sololearn.com/c2S471hyzeCB/?ref=app
2 ответов
+ 5
"""
map() use a callback function expecting one parameter... wich is called for each item: you don't (and can't) iterate over it ^^
"""
# Fixed code:
def add_five(x):
if x % 5 == 0:
return x + 5
nums = range(0,20)
result = list(map(add_five, nums))
print(result)
# Anyway, you can do it with filter() function to get only list of filtered result:
def div5(x):
return x % 5 == 0
def add5(x):
return x + 5
nums = range(0,20)
result = list(filter(div5, nums))
result = list(map(add5, result))
print(result)
# or even shortener use reduce() function (wich is in 'functools' module in Python3:
from functools import reduce
def red5(r,x):
if x % 5 == 0:
return r + [x+5]
else:
return r
nums = range(0,20)
result = list(reduce(red5, nums, []))
print(result)
# https://code.sololearn.com/cCEheB1RADvw/
+ 3
Previous post edited with link of answer code ^^