您的位置:首页 > 编程语言 > Python开发

python3 迭代器(itertools)

2018-01-08 21:06 405 查看
标准库中的itertools包里提供了很多有用的生成迭代器的函数。

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: