python map详解

# -- coding: utf-8 --

#1. 假设有一个数列,如何把其中每一个元素都翻倍?
list=[1,2,3,4,5]

list2=[i*2 for i in list]
print list2#[2, 4, 6, 8, 10]

#map方式
def double(x):
    return  x*2


list2=map(double,list)

print list2#[2, 4, 6, 8, 10]

#lamdba方式
list2=map(lambda x:x*2,list)

print list2#[2, 4, 6, 8, 10]

#两个集合相加
#这里的x,y是从list集合和list2集合中遍历出来的
list3=map(lambda x,y:x+y,list,list2)

print list3#[3, 6, 9, 12, 15]

'''
此外,当 map 中的函数为 None 时,结果将会直接返回参数组成的列表。
如果只有一组序列,会返回元素相同的列表,如果有多组数列,
将会返回每组数列中,对应元素构成的元组所组成的列表
'''
lst_1 = [1,2,3,4,5,6]
lst_2 = [1,3,5,7,9,11]
lst_3 = map(None, lst_1)
print lst_3#[1, 2, 3, 4, 5, 6]
lst_4 = map(None, lst_1, lst_2)
#将两个列表组成元组生成新的列表
print lst_4#[(1, 1), (2, 3), (3, 5), (4, 7), (5, 9), (6, 11)]

猜你喜欢

转载自blog.csdn.net/qq_38788128/article/details/80355208