您的位置:首页 > 编程语言 > Python开发

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

2014-09-17 22:28 666 查看
>>> 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__ = <built-in method __new__ of type object>

| 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)

<zip object at 0x01EF08F0>

>>> 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'}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: