python3 迭代器(itertools)

标准库中的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]
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值