zip()函数

浏览: 1042

一 代码引导:


actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
for a,n in zip(letter_codes,actions*2):
print (a,n)

运行结果:

87 Up

65 Left

83 Down

68 Right

82 Restart

81 Exit

119 Up

97 Left

115 Down

100 Right

114 Restart

113 Exit


  • lettercodes_actions = {65: 'Left', 83: 'Down', 68: 'Right', 97: 'Left', 119: 'Up', 114: 'Restart', 81: 'Exit', 82: 'Restart', 115: 'Down', 113: 'Exit', 87: 'Up', 100: 'Right'}
    for a,n in dict.items():
    print(a,n)

运行结果:

65 Left

83 Down

68 Right

81 Exit

119 Up

82 Restart

113 Exit

114 Restart

115 Down

97 Left

87 Up

100 Right


两段代码的区别:第一段更灵活


二 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__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.

zip()是内建函数,接受一系列可迭代参数,返回由tupple组成的list。如果参数长度不等,则返回list的长度,和参数长度最短的对象的长度相同。

三 扩展:

python与序列有关的函数有(sorted(),reversed(),enumerate(),zip())其中,sorted()和zip()返回一个序列(列表)对象,reversed()和enumerate()返回一个迭代器(类似序列)

Clipboard Image.png


四 用法:

 1 >>> z1=[1,2,3]
2 >>> z2=[4,5,6]
3 >>> result=zip(z1,z2)
4 >>> result
5 [(1, 4), (2, 5), (3, 6)]
6 >>> z3=[4,5,6,7]
7 >>> result=zip(z1,z3)
8 >>> result
9 [(1, 4), (2, 5), (3, 6)]

配合*使用,可以对zip过的对象进行解压

1 >>> zip(*result)
2 [(1, 2, 3), (4, 5, 6)]
推荐 0
本文由 shining52 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册