1.zip拉链
·功能:将两个列表合并起来,成为一个元素为元组的列表;
·演示如下:
>>> a = range(0,5) >>> b = range(5,10) >>> a [0, 1, 2, 3, 4] >>> b [5, 6, 7, 8, 9] >>> zip(a,b) [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)] >>> zip(b,a) [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4)]
·如果两个列表元素数量不一致,则zip会自动忽略:
>>> a = range(1,5) >>> b = [‘a‘, ‘b‘, ‘c‘] >>> a [1, 2, 3, 4] >>> b [‘a‘, ‘b‘, ‘c‘] >>> zip(a,b) [(1, ‘a‘), (2, ‘b‘), (3, ‘c‘)]
·利用zip的功能,可以造一个字典:
>>> key = [‘name‘, ‘girlfriend‘] >>> values = [‘xpleaf‘, ‘CL‘] >>> zip(key, values) [(‘name‘, ‘xpleaf‘), (‘girlfriend‘, ‘CL‘)] >>> dict(zip(key, values)) {‘girlfriend‘: ‘CL‘, ‘name‘: ‘xpleaf‘} >>> dict(zip(key, values))
2.map
·map的功能很强大,这里只提及其类似于zip的功能;
>>> a = range(1,5) >>> b = [‘a‘, ‘b‘, ‘c‘, ‘d‘] >>> map(a,b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ‘list‘ object is not callable >>> map(None,a,b) [(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, ‘d‘)]
·可以看到map需要指定第一个参数,因为map不会自动忽略两个列表数量不同的情况,指定参数作为数量不足列表的填充:
>>> b.pop() ‘d‘ >>> map(None, a, b) [(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, None)]
本文出自 “香飘叶子” 博客,请务必保留此出处http://xpleaf.blog.51cto.com/9315560/1695709
原文地址:http://xpleaf.blog.51cto.com/9315560/1695709