一 代码引导:
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()返回一个迭代器(类似序列)
四 用法:
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)]