map()接收两个参数,第一个参数是func,第二个参数是数组(list,set....),返回的是迭代器
实例1:
def compare(x):
if x > 1:
return 1
else:
return 0
data = [1, 2, 3, 4, 0.9, 0.5]
dflt = map(float, data)
dc = list(map(compare, data))
print(list(dflt))
print(list(map(lambda x:x**2, data)))
print(dc)
results:
[1.0, 2.0, 3.0, 4.0, 0.9, 0.5]
[1, 4, 9, 16, 0.81, 0.25]
[0, 1, 1, 1, 0, 0]
实例2:
对于两个变量
x = [1, 2, 3]
y = [1, 2, 3]
z = list(map(lambda a, b: a+b, x, y))
z = [2, 4, 6]