问题
如果一个可迭代对象的元素个数超过变量个数时,会抛出一个 ValueError 。 那么怎样才
能从这个可迭代对象中解压出N个元素出来?
record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
name, email, *phone_numbers = record
print(name) # ->Dave
print(email) # ->dave@example.com
print(phone_numbers) # ->['773-555-1212', '847-555-1212']
*trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
print(trailing) # ->[10, 8, 7, 1, 9, 5, 10]
print(current) # ->3
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)
'''
输出结果:
foo 1 2
bar hello
foo 3 4
'''
line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname,*fields,homedir,sh=line.split(":")
print(uname) # ->nobody
print(fields) # ->['*', '-2', '-2', 'Unprivileged User']
print(homedir) # ->/var/empty
print(sh) # ->/usr/bin/false
data = ['ACME', 50, 91.1, (2012, 12, 21)]
name,*_,(year,*_)=data
print(name) # ->ACME
print(year) # ->2012
参考文档:《python cookbook(第3版)高清中文完整版(###).pdf》