1
combinations:组合数最少的;组合数的下限,重复没有意义(所以不存在AA,BB, CC 这种组合),元素的顺序也没意义(AB和BA是一种组合);
product:返回笛卡尔积,组合数最多的,组合数的上限,重复和元素的顺序都有意义;
combinations_with_replacement:重复有意义(所以存在AA,BB, CC 这种组合),元素的顺序无意义(AB和BA是1种组合);
permutations:重复没有意义(所以不存在AA,BB, CC 这种组合),元素的顺序有意义(AB和BA是2种组合);
1 #组合学-生成器函数会从输入的多个元素中产出多个值 2 3 import itertools 4 5 6 group1 = list(itertools.combinations('ABC', 2)) 7 print('group1:', group1) 8 # [('A', 'B'), ('A', 'C'), ('B', 'C')] 9 10 group2 = list(itertools.combinations_with_replacement('ABC', 2)) 11 print('\ngroup2:', group2) 12 # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')] 13 14 group3 = list(itertools.permutations('ABC', 2)) 15 print('group3:', group3) 16 # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')] 17 18 group4 = list(itertools.product('ABC', repeat=2)) 19 print('group4:', group4) 20 # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
1
演示count, repeat, cycle的用法
1 #演示count, repeat, cycle的用法 2 import itertools 3 import operator 4 5 6 ct = itertools.count() 7 print(next(ct)) # 0 8 print("打印三次:", next(ct), next(ct), next(ct)) # 1 2 3 9 10 11 d = list(itertools.islice(itertools.count(1, .3), 3)) 12 print('d:', d) #[1, 1.3, 1.6] 13 14 15 cy = itertools.cycle('ABC') 16 print(next(cy)) # A 17 print("打印三次:",next(cy),next(cy),next(cy)) # B C A 18 19 cy_1 = list(itertools.islice(cy, 7)) 20 print("返回cy的7个元素:", cy_1) # 是接着前面已经输出的元素顺序,打印后面的7个元素 21 22 23 rp = itertools.repeat(7) 24 print('rp:',next(rp),next(rp)) # 7 7 25 26 27 d1 = list(itertools.repeat(8, 4)) 28 print('d1:', d1) # [8, 8, 8, 8] 29 30 31 d2 = list(map(operator.mul, range(11), itertools.repeat(5))) 32 print('d2:', d2) # [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
1
1
标签:函数,组合,list,生成器,cy,next,itertools,库中,print From: https://www.cnblogs.com/bravesunforever/p/17417692.html