python3 迭代器(itertools)
2018-01-08 21:06
405 查看
标准库中的itertools包里提供了很多有用的生成迭代器的函数。
例如:
用法举例:
或:
通过ctrl+c结束迭代。
用法类同count
用法类同count
输入:
输出:
举个例子,如果一个list = [p0 + p1 + p2 + p3],那么用accumulate计算后应该返回[p0,p0+p1,p0+p1+p2,p0+p1+p2+p3]
输入:
输出:
1. 无限迭代器(infinite iterators)
1.1 count
从一个指定数开始,按照设定无限迭代下去。例如:
count(1, 2) #从1开始的迭代器,每次增加2,即1,3,5,7,9, ... count(1) #1开始的迭代器,每次增加1,即1,2,3,4,5,...
用法举例:
from itertools import count for i in count(1): print(i) if i >=10: break
或:
import itertools counts = itertools.count(1) for n in counts: print n
通过ctrl+c结束迭代。
1.2 cycle
重复指定的那些元素。cycle('hello') #输出h,e,l,l,o,h,e,l,l....
用法类同count
1.3 repeat
把一个元素无限重复下去,如果提供第二个参数可以限定重复次数。repeat('A', 5) #重复输出5次A repeat('A') #无限重复输出A
用法类同count
2. 用于组合的函数
2.1 product
product(iter1,iter2, … iterN, [repeat=1]),创建一个迭代器,生成集合元素的笛卡尔积,repeat是一个关键字参数,指定重复生成序列的次数,默认为1.2.2 permulations
permutations(iter,r),返回iter中任意取r个元素做排列的迭代器。组合分顺序,比如ab, ba会都返回。2.3 combinations
combinations(iter,r),返回iter中任意取r个元素做排列的迭代器。组合不分顺序,比如ab, ba只返回一个ab。2.4 combinations_with_replacement
类似combinations,但是允许选取的元素重复。比如aa,bb。2.5 chain
组合原有迭代器得到新的迭代器。输入:
from itertools import product,permutations,combinations,combinations_with_replacement,chain print(list(product('abc', [1, 2, 3]))) print(list(permutations('abc', 2))) print(list(combinations('abc', 2))) print(list(combinations_with_replacement('abc', 2))) print(list(chain('abc', [1, 2, 3])))
输出:
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] [('a', 'b'), ('a', 'c'), ('b', 'c')] [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')] ['a', 'b', 'c', 1, 2, 3]
3. 另一些常见函数
3.1 takewhile
收集元素到迭代器,直到函数返回False停止。3.2 accumulate
accumulate 迭代器将返回累计求和结果,或者传入两个参数的话,由传入的函数累积计算的结果。默认设定为相加.举个例子,如果一个list = [p0 + p1 + p2 + p3],那么用accumulate计算后应该返回[p0,p0+p1,p0+p1+p2,p0+p1+p2+p3]
输入:
from itertools import accumulate,takewhile,chain num1 = list(accumulate(range(8))) print(num1) num2 = list(takewhile(lambda x: x<= 6, num1)) print(num2)
输出:
[0, 1, 3, 6, 10, 15, 21, 28] [0, 1, 3, 6]
相关文章推荐
- python基础===Python 迭代器模块 itertools 简介
- Python Iteration,itertools(Python迭代器,itertool个人总结)
- Python的itertools和迭代器
- python迭代器itertools
- python高级编程-Part2 高效的迭代器模块itertools
- Python迭代器包itertools(转)
- python 3-5 如何对迭代器做切片操作itertools.islice(open("test.txt"),0,10),迭代器消耗
- python itertools和迭代器的使用
- Python Iteration,itertools(Python迭代器,itertool个人总结)
- Python标准库:迭代器Itertools
- Python 迭代器 & __iter__方法
- python中itertools包无穷循环器的使用
- python itertools 模块完全掌握(1)
- python itertools
- python中itertools里的product和permutation
- Python常用内建模块之itertools
- Python天天美味(16) - 过滤字符串的技巧,map与itertools.imap
- python-collections/itertools
- Python模块 - itertools循环器模块