Wednesday, November 19, 2008

How to use zip and map function

There are many core build-in function in Python,today we'll meet zip and map.to illustrate,for instance,you have to list object,l1 and l2,now by use zip function you will get a tuple embeded list:
#python code:
>>> l1=['x','y','z']
>>> l2=[1,2,3]
>>> zip(l1,l2)
[('x', 1), ('y', 2), ('z', 3)]
>>>

Now,you can loop in this new zip model,and have the benefit from it,for example,you want to loop in these two list at the same time:
#python code:
>>> for (a,b) in zip(l1,l2):
print a,b


x 1
y 2
z 3
>>>

With this benefit,we can also create a dictionary object,for example:
#python code:
>>>d={}
>>> for (k,v) in zip(l1,l2):
d[k]=v
print d


{'x':1,'y':2,'z':3}
>>>

also there is a short way to create a dictionary object,use the build-in function,dict:
#python code:
>>>d={}
>>> d=dict(zip(l1,l2))
{'x':1,'y':2,'z':3}
>>>


Now,how about map function,map function is similar to zip,but for zip if your two list object has different number of items,then the zip function will truncate the larger one.for example:
#python code:
>>>l1=['x','y']
>>>l2=[1,2,3]
>>>zip(l1,l2)
>>>[('x',1),('y',2)]


but if you use the map function,you can stuff another parameter,to tell the function how to display that can't match items:
#python code:
>>>l1=['x','y']
>>>l2=[1,2,3]
>>>map(l1,l2)
>>>[('x',1),('y',2),(None,3)]

No comments: