Python常用函数备忘录

记录下一些常用函数的用法,备查

zip()

从名字就可以看出是用于配对压缩数据的,将需要配对的数据按照顺序一一配对形成元祖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> a = [1, 2, 3]
>>> b = ['x', 'y', 'z']
>>> zp = zip(a, b)
>>> list(zp)
[(1, 'x'), (2, 'y'), (3, 'z')]
>>> print(zp)
<zip object at 0x036CB8F0>
>>> zp[0]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
zp[0]
TypeError: 'zip' object is not subscriptable
>>> c=[10, 11, 12, 13, 14]
>>> zc = zip(a,c)
>>> zc
<zip object at 0x036C8FD0>
>>> list(zc)
[(1, 10), (2, 11), (3, 12)]

zip()会按照较短的一方数据进行截断,也可以多组数据进行配对:

1
2
3
4
>>> d = [123, 456]
>>> zd = zip(a, c, d)
>>> list(zd)
[(1, 10, 123), (2, 11, 456)]

同时zip()函数还可以用*操作符进行解压取消配对:

1
2
3
4
5
6
7
>>> a1, c1, d1 = zip(*zip(a, c, d))
>>> d1 == d
False
>>> d ==list(d1)
True
>>> d1
(123, 456)

注意上面代码中为什么d1 == dFalsed == list(d1)True?从最后一行应该可以理解,无论压缩还是解压返回的都是元祖,元祖用list()转化后后才是列表!