参考:itertools模块
product
相当于返回两个集合中数据的所有组合可能
from itertools import product a = (1, 2, 3) b = ('A', 'B', 'C') c = ('d', 'e', 'f') pros = product(a, b, c) count = 1 for elem in pros: print(f'{count:02}', "---", elem) count+=1 output: 01 --- (1, 'A', 'd') 02 --- (1, 'A', 'e') 03 --- (1, 'A', 'f') 04 --- (1, 'B', 'd') 05 --- (1, 'B', 'e') 06 --- (1, 'B', 'f') 07 --- (1, 'C', 'd') 08 --- (1, 'C', 'e') 09 --- (1, 'C', 'f') 10 --- (2, 'A', 'd') 11 --- (2, 'A', 'e') 12 --- (2, 'A', 'f') 13 --- (2, 'B', 'd') 14 --- (2, 'B', 'e') 15 --- (2, 'B', 'f') 16 --- (2, 'C', 'd') 17 --- (2, 'C', 'e') 18 --- (2, 'C', 'f') 19 --- (3, 'A', 'd') 20 --- (3, 'A', 'e') 21 --- (3, 'A', 'f') 22 --- (3, 'B', 'd') 23 --- (3, 'B', 'e') 24 --- (3, 'B', 'f') 25 --- (3, 'C', 'd') 26 --- (3, 'C', 'e') 27 --- (3, 'C', 'f')
例子2:二进制数三位数的所有可能
a = (0, 1) b = (0, 1) c = (0, 1) pros = product(a, b, c) count = 1 for elem in pros: print(f'{count:02}', "---", elem) count+=1 output: 01 --- (0, 0, 0) 02 --- (0, 0, 1) 03 --- (0, 1, 0) 04 --- (0, 1, 1) 05 --- (1, 0, 0) 06 --- (1, 0, 1) 07 --- (1, 1, 0) 08 --- (1, 1, 1)
chain 就是合并成一个 iter
from itertools import chain [e for e in chain([2, 3], {3, 4}, (3,4))] output: [2, 3, 3, 4, 3, 4]