python中itertools_python中的itertools模块

简介:

itertools——创建高效迭代器的Python模块。

itertools模块可创建的迭代器一般分为三类:

1.无限迭代器

2.终止于最短输入序列的迭代器

3.组合生成器

一.无限迭代器

1 count(),接受两个参数,第一个是开始的数字,第二个是步幅,默认从0开始,用法如下:

importitertools

c= itertools.count(10,2)for i inc:if i > 20:break

print(i)#10 12 14 16 18 20

2 cycle(),接受一个参数,该参数是迭代器对象(列表,字符串等),会循环生成迭代器中的元素:

importitertools

c= itertools.cycle([1,2,3])

i= 1

for j inc:if i > 7:break

print(j)

i+= 1

#1 2 3 1 2 3 1

3 repeat(),接受两个参数,用于生成第一个参数n次:

importitertoolsfor i in itertools.repeat([1,2,3],4):print(i)#[1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]

二.有限迭代器

1 chain(),接受多个迭代器对象作为参数,并把它们连接起来chain('abc', [1, 2, 3])

2 compress(data, selectors), 根据后面的参数过滤前面的参数,两个参数都需要是迭代器对象

importitertools

a= [1,2,3,4]

b= 'abc'c=itertools.compress(a,b)for i inc:print(i)#1 2 3

3 dropwhile(pre,iterable),pre参数是一个函数,当pre(i)是Ture是,返回该项以及后面所有项

4 groupby(iterable[,keyfunc]),其中iterable 是一个可迭代对象,keyfunc 是分组函数,用于对 iterable 的连续项进行分组,

如果不指定,则默认对 iterable 中的连续相同项进行分组,返回一个 (key, sub-iterator) 的迭代器。

5 ifilter(function orNone,sequence),将 iterable 中 function(item) 为 True 的元素组成一个迭代器返回,

如果 function 是 None,则返回 iterable 中所有计算为 True 的项

6 tee(iterable[,n]),tee 用于从 iterable 创建 n 个独立的迭代器,以元组的形式返回,n 的默认值是 2。

importitertoolsfor i in itertools.tee('abc',5):print(list(i))

三.组合生成器

1 permutations(iterable[,r]),用于生成一个排列,r是生成排列的元素长度,不指定则为默认长度

1 print list(it.permutations('abc'))2 print list(it.permutations('abc', 2))3 #[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

4 #[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

2 combinations(iterable,r), 求序列的组合,其中,r 指定生成组合的元素的长度,是必需的参数

3 combinations_with_replacement(iterable, r),生成的组合包含自身元素

1 print list(it.combinations_with_replacement('abc', 2))2 #[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值