+ 1
This works too.
def add_five(x): return x + 5 nums = [11, 22, 33, 44, 55] result= list (add_five(i) for i in nums) print(result) map function is a little complicated, need more sample to understand better.
2 Respostas
+ 2
# map can apply a function to each item in an iteratable.
# map() provides an alternative to your example approach
# If you read about functional programming in general
# https://docs.python.org/3.5/howto/functional.html
# or David Mertz, Functional Programming in Python
# the mapping concept is made clearer
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
# your generator example
result= list (add_five(i) for i in nums)
print(result)
# the same thing with a mapped object
# for every position 'x' in nums make the value 5 higher
# [11,22,33,44]->[16,27,38,60]
add_five = list(map(lambda x: x+5,nums))
print(add_five)
# list comprehension will do the same thing too
comp = [i+5 for i in nums]
print(comp)
# another example of the general principle of mapping
# for every character in the string change it to
# it's ASCII number
my_string = 'hello'
change_letters = ''.join(map(lambda x:str(ord(x))+' ',my_string))
print(change_letters)
# but it can be done with a comprehension too
print(''.join([str(ord(x))+' 'for x in my_string]))