Python3的迭代器

来源:互联网 发布:网络监控能看到啥 编辑:程序博客网 时间:2024/06/11 11:44

迭代是访问集合元素的一种方式,迭代器是一个可以记住遍历位置的对象;字符串,列表或元组对象都可用于创建迭代器。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束;迭代器只能往前不会后退,迭代到最后会从头再开始。

迭代器有两个基本的方法:iter() 和 next()。

>>>list=['a','b','c','d']>>>it=iter(list)   #iter方法用序列创建了一个迭代器对象it>>>type(it)<class 'list_iterator'>>>>print(next(it)) #next方法调用迭代器对象ita>>>print(next(it))b

Python构造迭代的模块——itertools模块

(count,cycle,islice)

>>>import itertools>>>dir(itertools)['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']

count(n):创建一个迭代器,生成从n开始的连续整数,如果忽略n,则从0开始计算(注意:此迭代器不支持长整数)。

>>> from itertools import count>>> counter=count(12)   #从12开始向后计数>>> next(counter)12>>> next(counter)13>>> co=count()         #未给定起始值,从0开始向后计数>>> next(co)0>>>next(co)1

cycle(iterable):创建一个迭代器,对可迭代对象iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本,此副本用于返回循环中的重复项。

from itertools import cycle>>> nums=cycle(('a','b','c'))>>> next(nums)'a'>>> next(nums)'b'>>> next(nums)'c'>>> next(nums)'a'>>> for num in nums:  #死循环!    print(num)

islice(iterable, start, stop , step)创建一个迭代器,生成项的方式类似于切片返回值,如果省略了start,迭代将从0开始,如果省略了step,步幅将采用1。

from itertools import islicenums = cycle([1,2,3])limited = islice(nums, 0, 5)for item in limited:    print(item)>>>12312
原创粉丝点击