python中笛卡尔积源码及实际使用

问题:对于多个集合或列表,每次只从这多个集合或列表中取出一个元素,求所有的组合方式?

如何自己写可能就想到多重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)

如上所示,即将多个列表放在一个列表内,然后在这个大列表前面加一个*.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值