python itertools模块使用

itertools模块使用

itertools 简介

简单来说itertools是python提供的一个模块用于创建自定义的迭代器

itertools提供的功能

chain

与其名称意义一样,给它一个列表如lists/tiples/iterables,链接在一起;返回iterables对象

例子

1
2
3
4
a = ['a', 'b', 'c']
b = [1, 2, 3]
print(list(itertools.chain(a,b))) // => ['a' ,'b', 'c', 1, 2, 3]
print(tuple(itertools.chain(a,b))) // => ('a' ,'b', 'c', 1, 2, 3)}

count

生成无界序列 count(a,b) a是起始数,b是步长

filterfalse

filterfalse(contintion,data)迭代过滤条件为false的数据,如果条件为空,返回data中为false的想

compress

返回我们需要使用的元素

starmap

针对list的每一项,调用函数的功能

repeat

repeat(object,time) 重复time次

dropwhile

dropwhile(func,sep);当函数func执行返回假时,开始迭代序列

1
dropwhile(lambda x: x<5, [1,4,6,4,1]) => 6 4 1

takewhile

takewhile(predicate, iterable);返回序列,当predicate为true时截止

product

product(iter1,iter2, …iterN,[repect=1])创建一个迭代器,生成表示iter1,iter2等组成的笛卡尔积的元组

1
product('ab','cd')// => ac ad bc bd

permutations()

permutations(p[,r]);返回p中任意取r个元素做排列的元组的迭代器

combinations()

combinations(iterable,r);创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序

不重复输出相同值