python zip函数同时遍历两个数组和构造字典

>>> help(zip)
Help on class zip in module builtins:


class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __next__(...)
 |      x.__next__() <==> next(x)
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ =

 |      T.__new__(S, ...) -> a new object with type S, a subtype of T



>>> A=[1,2,3]
>>> B=[4,5,6]
>>> bb=zip(A,B)

>>> for i in bb:
print(i)



(1, 4)
(2, 5)
(3, 6)


1.通过zip同时遍历两个数组

>>> for i,v in bb:
print(i,v)



1 4
2 5
3 6

通过这种方式同时遍历两个list,是不是很方便呢?但是如果两个list的长度不一样,则长的那一个的多余元素会被截掉。



2.通过zip构造字典

>>> key=['username','pwd']
>>> values=['nini','1qaz']
>>> bb=dict(zip(key,values))
>>> print(bb)
{'pwd': '1qaz', 'username': 'nini'}

你可能感兴趣的:(python编程)