迭代器与常见内置函数
可迭代对象
对象能通过.方法调用__iter__()的就是可迭代对象,基本数据类型中有字符串、列表、字典、元组、集合,还有文件对象也是可迭代对象(也是迭代器)。
迭代器
既能调用__iter__()又能调用__next__()方法的就是迭代器,迭代器给不支持索引取值的数据类型提供了取值的方法。
for循环本质就是调用in后的数据对象的__iter__()方法,然后不停的__next__(),通过try-except捕获异常停止for循环。
# for循环模拟
l = [1,2,3,4]
i = iter(l) # 或l.__iter__() 获得列表l的迭代器
while True:
try:
res = next(i) # 等同i.__next__()
print(res)
except Exception:
break
常见的内置方法
# min|max
l = [10,55,999,145,87]
res = max(l)
print(res) # 999
# max还能传入函数,匿名函数取得每个对象键age对应的值比较,返回最大age的字典对象
l2 = [
{'name':'xie','age':14},
{'name':'san','age':19},
{'name':'lin','age':8},
{'name':'ming','age':26}
]
res = max(l2,key=lambda x:x.get('age'))
print(res) # {'name': 'ming', 'age': 26}
# filter 筛选满足条件的对象返回一个迭代器
l = [
{'name':'xie','score':61},
{'name':'san','score':78},
{'name':'lin','score':59},
{'name':'ming','score':54},
]
res = filter(lambda x:x.get('score') >= 60,l)
print(list(res)) # [{'name': 'xie', 'score': 61}, {'name': 'san', 'score': 78}]
# reduce 累加
l = [1,2,3,4,5]
res = reduce(lambda x, y: x+y, l)
print(res) # 15
# reduce还能指定初始值
res1 = reduce(lambda x, y: x+y, l, 10)
print(res) # 25
# zip 拉链
l1 = ['name','age','gender']
l2 = ['xie',18,'male']
dic = {k:v for k,v in zip(l1,l2)}
print(dic) # {'name':'xie','age':18,'gender':'male'}

浙公网安备 33010602011771号