1.2 解压可迭代对象赋值给多个变量

来源:互联网 发布:sd卡数据恢复手机版 编辑:程序博客网 时间:2024/06/05 14:19

如果一个可迭代对象的元素个数超过变量个数时,会抛出一个 ValueError 。 那么怎样才能从这个可迭代对象中解压出 N 个元素出来?
解决方案:星号表达式
1. 比如有100个元素的列表,需要排除第一二个元素和末尾元素。

I = [num for num in range(1,101)]first,second,*middle,last = Iprint(middle) 

2.假设你现在有一些记录列表,每条记录包含一个名字、邮件,接着就是不确定数量的QQ。

info =['join','66666666@.qq.com','138238221','11257889']name,email,*qq = info

3.星号表达式也可以用在列表开始,
比如有5门成绩和总分的列表,需要查看平均分和总分。

score = [95,98,95,75,85,448]*score,allScore = scoreavg_score = sum(score)/len(score) print(avg_score,allScore)

4.迭代解压

records = [    ('value',10 , 20),    ('id', 'raspberry'),    ('foo', 3, 4),]def value(x, y):    print('value', x, y)def id(s):    print('id', s)def foo(x,y):    print('foo',x,y)for tag, *args in records:    if tag == 'value':        value(*args)    elif tag == 'id':        id(*args)    elif tag == 'foo':        foo(*args)

5.分解字符串。

line = "python:c++,java,go,ruby"first,*middle,tail = line

6.实现递归

def sum(items):    head, *tail = items    return head + sum(tail) if tail else headnum = [1,3,5,7,9]sum(num)
原创粉丝点击