python中itertools里的product和permutation
平时经常碰到全排列或者在n个数组中每个数组选一个值组成的所有序列等等问题,可以用permutation和product解决,很方便,所以在此mark一下吧
直接上代码
from itertools import * if __name__ == '__main__': for j in permutations([2,5,6]): print(j) ''' (2, 5, 6) (2, 6, 5) (5, 2, 6) (5, 6, 2) (6, 2, 5) (6, 5, 2) ''' list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] for i in product(list1,list2,list3): print(i) ''' (1, 4, 7) (1, 4, 8) (1, 4, 9) (1, 5, 7) (1, 5, 8) (1, 5, 9) (1, 6, 7) (1, 6, 8) (1, 6, 9) (2, 4, 7) (2, 4, 8) (2, 4, 9) (2, 5, 7) (2, 5, 8) (2, 5, 9) (2, 6, 7) (2, 6, 8) (2, 6, 9) (3, 4, 7) (3, 4, 8) (3, 4, 9) (3, 5, 7) (3, 5, 8) (3, 5, 9) (3, 6, 7) (3, 6, 8) (3, 6, 9) ''' #[list2]*3表示[list2,list2,list2] #最前面的*号表示将[list2,list2,list2]列表解析成独立的参数 #也就是相当于入参是(list2,list2,list2) for i in product(*[list2]*3): print(i) ''' (4, 4, 4) (4, 4, 5) (4, 4, 6) (4, 5, 4) (4, 5, 5) (4, 5, 6) (4, 6, 4) (4, 6, 5) (4, 6, 6) (5, 4, 4) (5, 4, 5) (5, 4, 6) (5, 5, 4) (5, 5, 5) (5, 5, 6) (5, 6, 4) (5, 6, 5) (5, 6, 6) (6, 4, 4) (6, 4, 5) (6, 4, 6) (6, 5, 4) (6, 5, 5) (6, 5, 6) (6, 6, 4) (6, 6, 5) (6, 6, 6) '''