机关网站制度建设,罗湖住房和建设局网站官网,wordpress 中文优化版,外国网站dnspython中迭代器的使用是最广泛的#xff0c;凡是使用for语句#xff0c;其本质都是迭代器的应用。
从代码角度看#xff0c;迭代器是实现了迭代器协议的对象或类。迭代器协议方法主要是两个#xff1a;
__iter__()__next__()
__iter__()方法返回对象本身#xff0c;他是…python中迭代器的使用是最广泛的凡是使用for语句其本质都是迭代器的应用。
从代码角度看迭代器是实现了迭代器协议的对象或类。迭代器协议方法主要是两个
__iter__()__next__()
__iter__()方法返回对象本身他是for语句使用迭代器的要求。
__next__()方法用于返回容器中下一个元素或者数据。当容器中的数据用尽时引发StopIteration异常。
任何一个类只要实现了或者具有这两个方法就可以称其为迭代器也可以说是可迭代的。
内置迭代器工具
Python语言中已经内建了一个用于产生迭代器的函数iter()另外标准库的itertools模块中还有丰富的迭代器工具。
1.内建迭代器函数
内建的iter()函数有两种使用方法原型如下
iter(iterable) 参数iterable为可迭代类型
iter(callable,sentinel) 参数callable为可调用类型参数sentinel称为‘哨兵’即当第一个参数调用返回值等于第二个参数的值时迭代或遍历停止。
2.itertools中常用的工具函数
itertools中提供了近二十种迭代器函数主要分为三类
无限迭代器
count(start,[step]) # 从start开始以step为步进行技术迭代 import itertools for i in itertools.count(1,3): print(i) if i10: break 1 4 7 10 cycle(seq) # 无线循环迭代seq x0 for i in itertools.cycle([a,b]): print(i) x1 if x6: break a b a b a b repeat(elem,[n]) # 循环迭代elem list(itertools.repeat(3,6)) [3, 3, 3, 3, 3, 3] 迭代短序列
chain(p,q,...) 链接迭代将pq连接起来迭代就像从一个序列中迭代 list(itertools.chain([1,2],[8,9])) [1, 2, 8, 9] compress(data,selectors) 依据selectors中的值选择迭代data序列中的值 list(itertools.compress([1,2,3,4,5,6,7,8,9,10],[1,,2,None,{a:3},{4},[],{},5,0])) [1, 3, 5, 6, 9] dropwhile(pred,seq) 当pred对序列元素处理结果为假时开始迭代seq后所有值 list(itertools.dropwhile(lambda x:x6,[8,9,1,2,6,7])) [1, 2, 6, 7] filterfalse(pred,seq) 当pred处理为假的元素 list(itertools.filterfalse(lambda x:x6,[8,9,1,2,6,7])) [1, 2, 6] takewhile(pred,seq) 与dropwhile相反 list(itertools.takewhile(lambda x:x6,[8,9,1,2,6,7])) [8, 9] tee(it,n) 将it重复n次进行迭代 for its in itertools.tee([1,2,3],3): for i in its: print(i) 1 2 3 1 2 3 1 2 3 zip_longest(p,q,...)
组合迭代器
product(p,q,...[,n]) 迭代排列出所有的排列 list(itertools.product(abcd, 123)) [(a, 1), (a, 2), (a, 3), (b, 1), (b, 2), (b, 3), (c, 1), (c, 2), (c, 3), (d, 1), (d, 2), (d, 3)] permutations(p,r) 迭代序列中r个元素的排列 list(itertools.permutations(abcd, 2)) [(a, b), (a, c), (a, d), (b, a), (b, c), (b, d), (c, a), (c, b), (c, d), (d, a), (d, b), (d, c)] combinations(p,r) 迭代序列中r个元素的组合 list(itertools.combinations(abcd, 2)) [(a, b), (a, c), (a, d), (b, c), (b, d), (c, d)]