map()函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
用法:
第一种:map(f, list)
fruits = ['apple', 'banana', 'watermelon', 'orange']
def f(x):
x = x + 's'
return x
orchard = map(f, fruits)
for fruit in orchard:
print('You have ' + fruit)
输出:
You have apples
You have bananas
You have watermelons
You have oranges
第二种:map(f(x,y), list1, list2)
first_names = ['Tom', 'jerry', 'collapse', 'Eva', 'WALY']
last_names = ['green', 'pom', 'day', 'smart', 'keven']
def f(x, y):
x = x[:1].upper() + x[1:].lower()
y = y[:1].upper() + y[1:].