用列表解析写zip()函数

1 def myzip(*args):
2     seq=[list(s) for s in args]
3     #you cannot add * before args
4     res=[]
5     while all(seq):
6         res.append(tuple([s.pop(0)for s in seq]))
7         #
8     print res

all()函数,确定了选取最短的序列来截断。

[(1, 2), (2, 3)]

也可以利用any函数确定最长

1 def myzip(*args):
2     seq=[list(s) for s in args]
3     res=[]
4     while any(seq):
5         res.append(tuple([(s.pop(0)if s else None)for s in seq]))
6 #由于pop无法从[]中读出数,那么增加一个判断
7     print res
8 myzip([1,2],[2,3,4])

结果:

[(1, 2), (2, 3), (None, 4)]

posted @ 2016-09-21 18:48  dreamfor  阅读(140)  评论(0)    收藏  举报