1.map()函数
map()函数的目的是对每个成员迭代执行一个函数操作,最后返回的是一个列表
map(function, sequence[, sequence, ...]) -> list
In [82]: def add100(x): ....: return x+100 ....: In [83]: map(add100,(44,22,66)) Out[83]: [144, 122, 166]
定义一个函数add100(x),map(add100,(44,22,66))就是迭代的对每个数字进行add100(x)的操作,最后返回一个列表数据
In [84]: def abc(a,b,c): ....: return a*100 + b*10 + c ....: In [85]: map(abc,(1,2,3),(4,5,6),(7,8,9)) Out[85]: [147, 258, 369]
如果需要迭代执行的函数需要多个参数,那么就为map()提供多个元组
In [91]: map(None,range(3)) Out[91]: [0, 1, 2] In [92]: map(None,range(3)) Out[92]: [0, 1, 2] In [93]: map(None,range(3),‘abc‘,(44,55,66)) Out[93]: [(0, ‘a‘, 44), (1, ‘b‘, 55), (2, ‘c‘, 66)] In [94]: map(None,range(3),‘abc‘) Out[94]: [(0, ‘a‘), (1, ‘b‘), (2, ‘c‘)] In [95]: map(None,range(3),range(3)) Out[95]: [(0, 0), (1, 1), (2, 2)]
如果想将一行字符串转换成字典就可以这样
In [97]: d=‘zk_version\t3.4.6‘ In [99]: map(str.strip,d.split(‘\t‘)) Out[99]: [‘zk_version‘, ‘3.4.6‘] In [100]: key,value=map(str.strip,d.split(‘\t‘)) In [101]: key Out[101]: ‘zk_version‘ In [102]: value Out[102]: ‘3.4.6‘ In [103]: result[key]=value In [104]: result Out[104]: {‘zk_version‘: ‘3.4.6‘}
2.zip()函数
zip()的目的是返回一个元组列表
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
In [107]: L1=[1,2,3,4] In [108]: L2=[‘a‘,‘b‘,‘c‘,‘d‘] In [109]: zip(L1,L2) Out[109]: [(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, ‘d‘)] In [110]: L3=[10.0,20.0,30.0,40.0] In [111]: zip(L1,L2,L3) Out[111]: [(1, ‘a‘, 10.0), (2, ‘b‘, 20.0), (3, ‘c‘, 30.0), (4, ‘d‘, 40.0)]
3.dict()函数
dict()最后返回的是一个字典类型
In [141]: L1 Out[141]: [1, 2, 3, 4] In [142]: L2 Out[142]: [‘a‘, ‘b‘, ‘c‘, ‘d‘] In [143]: zip(L2,L1) Out[143]: [(‘a‘, 1), (‘b‘, 2), (‘c‘, 3), (‘d‘, 4)] In [144]: dict(zip(L2,L1)) Out[144]: {‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4} In [145]: dict(a=10,b=20,c=30) Out[145]: {‘a‘: 10, ‘b‘: 20, ‘c‘: 30} In [146]: dict([(‘a‘,100),(‘b‘,200),(‘c‘,300)]) Out[146]: {‘a‘: 100, ‘b‘: 200, ‘c‘: 300}
参考资料:
https://docs.python.org/2/library/functions.html#zip
http://stackoverflow.com/questions/672172/using-python-map-and-other-functional-tools
https://infohost.nmt.edu/tcc/help/pubs/python/web/map-function.html
时间: 2024-11-06 12:53:57