问题:对于多个集合或列表,每次只从这多个集合或列表中取出一个元素,求所有的组合方式?
如何自己写可能就想到多重for循环,但是,当使用多重for循环时,如果集合或列表数过多,则非常繁琐!
python标准库提供了笛卡尔积这一方法:itertools.product()
源码:(改动了一点点,只针对这一问题)
def product(*args):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
pools = map(tuple, args)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
if __name__ == '__main__':
a= [1,2,3]
b = [5,6,7]
for i in product(a,b):
print(i)
结果:
(1, 5)
(1, 6)
(1, 7)
(2, 5)
(2, 6)
(2, 7)
(3, 5)
(3, 6)
(3, 7)
实际使用时,可能存在任意个列表或集合,此时可以对任意个列表包装起来,实际操作:
if __name__ == '__main__':
a= [1,2,3]
b = [5,6,7]
c = [a,b]
for i in product(*c):
print(i)
如上所示,即将多个列表放在一个列表内,然后在这个大列表前面加一个*.