Monday, April 28, 2008

zip() function,What does that mean and how to use it?

Some time we have the requirement like this,get the element from two lists and print(or process ) them in sequence.For example,we have two list [1,2,3] and [4,5,6] , and we want to implement like build a new list[5,7,9]( [(1+4),(2+5),(3+6)]).how to do it.At before time.we can use the function map():
a=[1,2,3]
b=[4,5,6]
c=[]
for x in map(None,a,b):
c.append(x[0]+x[1])

but it's not a good solution,especially that None argument:)
Now,we have another better choose.zip() function.What's it means?
zip() function will return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

for example:
a=[1,2,3]
b=[4,5,6]
c=[]
for i in zip(a,b):
c.append(x[0]+x[1])

it's better understand,isn't it?

No comments: