产品开发与python_Python组合和产品

这是一种更强大/更通用的方式来执行您想要的事情.我首先定义一个辅助函数:

from itertools import combinations, chain, product

def subsets_of_length(s, lengths):

return chain.from_iterable(combinations(s,l) for l in lengths)

它产生以下输出:

>>>> list(subsets_of_length(['a','b','c'], range(2,4)))

[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

>>>> list(subsets_of_length(['d','e'], range(0,2)))

[(), ('d',), ('e',)]

现在我们要组合两个或多个子集,如下所示

>>>> for choices in product(

subsets_of_length(['a','b','c'], range(2,4)),

subsets_of_length(['d','e'], range(0,2)),

):

print(' '.join(str(subset) for subset in choices))

('a', 'b') ()

('a', 'b') ('d',)

('a', 'b') ('e',)

('a', 'c') ()

('a', 'c') ('d',)

('a', 'c') ('e',)

('b', 'c') ()

('b', 'c') ('d',)

('b', 'c') ('e',)

('a', 'b', 'c') ()

('a', 'b', 'c') ('d',)

('a', 'b', 'c') ('e',)

但是我们希望将这些元组链接在一起.因此,我们应该做

>>>> for choices in map(chain.from_iterable,product(

subsets_of_length(['a','b','c'], range(2,4)),

subsets_of_length(['d','e'], range(0,2)),

)):

print(' '.join(column for column in choices if column))

a b

a b d

a b e

a c

a c d

a c e

b c

b c d

b c e

a b c

a b c d

a b c e

您所编辑问题的代码为:

for choices in map(chain.from_iterable,product(

subsets_of_length(['AA','AS','AD'], [1]), #only one of these

subsets_of_length(['BB','BC'], [1,2]), #at least one of these

subsets_of_length(['CD','CF','CG'], [0,1,2,3]), #All, 1, 2 or none of these

)):

print(' '.join(column for column in choices if column))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值