方法
在一个可迭代对象的元素个数超过变量的个数时,就会抛出一个 valueError的错误,为了解决这个错误,使用如下方法
def drop_first_last(grades): first, *middle, last = grades return avg(middle)
如:
>>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212') >>name,email,*phone_number=record >>name Dave >>eamil dave@example.com >>phone_number '773-555-1212', '847-555-1212'
>>> *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
>>> trailing
[10, 8, 7, 1, 9, 5, 10]
>>> current
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' >>>
如果你要解压一些元素,并丢弃它们,你就不能只是简单的使用* ,应该使用一些丢弃名称例如: _ 或者ign
>>> record = ('ACME', 50, 123.45, (12, 18, 2012)) >>> name, *_, (*_, year) = record >>> name 'ACME' >>> year 2012 >>>
字符串的切割
>>> items = [1, 10, 7, 4, 5, 9] >>> head, *tail = items >>> head 1 >>> tail [10, 7, 4, 5, 9] >>>