python函数zip
zip函数可接受任意序列为参数,返回一个以tuple为元素的列表:
>>> a=[1,2,3] >>> b=[4,5,6] >>> zip(a,b) [(1, 4), (2, 5), (3, 6)] >>>
当两个序列元素个数不一致时,以较少的为准:
>>> a [1, 2, 3] >>> c [7, 8, 9, 10] >>> zip(a,c) [(1, 7), (2, 8), (3, 9)] >>>
三个序列作为参数:
>>> a [1, 2, 3] >>> b [4, 5, 6] >>> c [7, 8, 9, 10] >>> zip(a,b,c) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>>
zip的unzip操作:
>>> a [1, 2, 3] >>> b [4, 5, 6] >>> c [7, 8, 9] >>> m=zip(a,b,c) >>> m [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> zip(*m) [(1, 2, 3), (4, 5, 6), (7, 8, 9)] >>> list(zip(*m)[0]) [1, 2, 3] >>>
示例:
>>> zip(*[a]*3) [(1, 1, 1), (2, 2, 2), (3, 3, 3)] >>>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。