Python Cookbook 读书笔记
举个例子:
>>> p = (1, 2)
>>> x, y = p
>>> x
1
>>> y
2
>>>
>>> data = [ 'clip', 23, 172, (2018, 10, 22) ]
>>> name, age, height, birth= data
>>> name
'clip'
>>> birth
(2018, 10, 22)
>>> name, age, height, (year, mon, day) = data
>>> name
'clip'
>>> year
2018
>>> mon
10
>>> day
22
>>>
>>> s = 'Hello'
>>> a, b, c, d, e = s
>>> a
'H'
>>> b
'e'
>>> e
'o'
>>>
有的时候,拆包后的元素我们不一定全部需要,对于不需要的元素可以用任意符号占位
>>> data = [ 'clip', 23, 172, (2018, 10, 22) ]
>>> _, age, height, _ = data
>>> age
23
>>> height
172
>>> *_, height, birth = data
>>> height
172
>>> birth
(2018, 10, 22)
>>> name, *_, (*_, day) = data
>>> name
'clip'
>>> day
22
>>>
1.拆包元祖
>>> info = ('Clip', '[email protected]', '123-456-789', '000-123456789')
>>> name, email, *phone_numbers = info
>>> name
'Dave'
>>> email
'[email protected]'
>>> phone_numbers
['123-456-789', '000-123456789']
>>>
注意: 使用 * 拆包出来的变量永远都是列表类型, 使用的时候不用再去判断类型
2. 拆包嵌套类型
下面是一个列表中嵌套元祖的类型
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]
def do_foo(x, y):
print('foo', x, y)
def do_bar(s):
print('bar', s)
for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif tag == 'bar':
do_bar(*args)
3. 分割字符串
>>> line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
>>> uname, *fields, homedir, sh = line.split(':')
>>> uname
'nobody'
>>> homedir
'/var/empty'
>>> sh
'/usr/bin/false'
>>>