该模块基本都是生成迭代器,需要用list 之类的把东西放进去
1. chain()
把 list/tuple/set/iterables 连在一起,返回课迭代对象
array = [1, 10, 9, 12, 3, 4] import itertools print(list(itertools.chain(array,array[::-1]))) # 如果不加list 返回的是<itertools.chain object at 0x10edbd0d0> # 加了list() 返回[1, 10, 9, 12, 3, 4, 4, 3, 12, 9, 10, 1]
2. count()
生成无界限序列,count(start = 0,step = 1)
for item in itertools.count(100, 2): #从100 开始,步长为2 返回100,102...... i += 1 if i > 10: break
3. ffilterfalse(条件,数据)
迭代过滤条件为false的数据,如果条件为空,返回data 中为false 的项,返回的是不符合条件的数据
a =[23, 20, 44, 32,78,10] print(list(itertools.filterfalse(lambda x : x < 20, a))) # [23, 20, 44, 32, 78]
4. compress()
返回a 对应b的真值
c = ['a','c','d','e','f','h','t','d'] d = [1,0,0,0,0,0,0,1] print(list(itertools.compress(c,d))) #['a', 'd']
5.starmap()
针对列表中的每一个元素,进行函数运算
print(list(itertools.starmap(max,[[2,45,87,14,5],[24,34,23],[2,5,3]]))) # [87, 34, 5]
6. takewhile()
与dropwhile()相反
print(list(itertools.takewhile(lambda x: x<10, [1,4,8,9,11,6,4,1]))) # [1, 4, 8, 9] 当返回假时停止输出迭代值
7. repeat()
repeat( 对象,重复几次)
print(list(itertools.repeat(25,4))) # [25, 25, 25, 25]
8.islice()
print(list(itertools.islice('abcdefghijklmnopqrstuvwxyz',1,25,3))) # ['b', 'e', 'h', 'k', 'n', 'q', 't', 'w'] (值[,开始],结束[,步长])
9.dropwhile()
当返回假时, 开始迭代
print(list(itertools.dropwhile(lambda x: x<10, [1,4,8,9,11,6,4,1]))) # [11, 6, 4, 1] 当迭代到11 时,大于10 返回false,即开始输出迭代数据
10.permutations()
permutation(元素,n) 在元素中取 n 个元素进行排列组合
print(list(itertools.permutations('abd',2))) # [('a', 'b'), ('a', 'd'), ('b', 'a'), ('b', 'd'), ('d', 'a'), ('d', 'b')]
11. product()
product(iter1,iter2, ... iterN, [repeat=1]) 生成一个迭代器,相当于是每个元素的笛卡尔积
print(list(itertools.product('ab','xy'))) # [('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y')] print(list(itertools.product('ab',repeat=2))) # [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
12.combinations_with_replacement() 不知道这个和permutation() 有什么区别
与 combination相似 但是重复的
print(list(itertools.combinations_with_replacement('abd',2))) # [('a', 'a'), ('a', 'b'), ('a', 'd'), ('b', 'b'), ('b', 'd'), ('d', 'd')]
13. combinations()
类似于permutation()
但combination() 是不重复的
print(list(itertools.combinations('abd',2))) # [('a', 'b'), ('a', 'd'), ('b', 'd')]
14. groupby()
将相邻相同的元素合并在一起,返回两个值 一个是a(类似于标题) 一个是迭代器, 不区分大小写
for a,b in itertools.groupby('aaabb11ss2212d'): print(a,list(b)) # a ['a', 'a', 'a'] # b ['b', 'b'] # 1 ['1', '1'] # s ['s', 's'] # 2 ['2', '2'] # 1 ['1'] # 2 ['2'] # d ['d']
浙公网安备 33010602011771号