[英]Using Itertools to create a list of combination of elements from multiple lists
I have the following:我有以下几点:
a = [i/100 for i in range(5,105,5)]
a.append(0)
b = [i/100 for i in range(5,105,5)]
b.append(0)
c = [i/100 for i in range(5,105,5)]
c.append(0)
d = [i/100 for i in range(5,105,5)]
d.append(0)
e = [i/100 for i in range(5,105,5)]
e.append(0)
combs = itertools.product(a,b,c,d,e)
'combs' would give me all possible combinations of a,b,c,d and e. “梳子”会给我所有可能的 a、b、c、d 和 e 组合。 However, I was wondering if I could combine them so that they add up to 1.但是,我想知道是否可以将它们组合起来,使它们加起来为 1。
Thank you.谢谢你。
As far as I know there is no builtin way in itertools to do this.据我所知, itertools 中没有内置的方法来做到这一点。 You can evidently filter the result, but this would be rather inefficient : one expects only a small amount of combinations to add up to sum
.您显然可以过滤结果,但这会相当低效:人们期望只有少量组合加起来为sum
。
Given all fed values are positive (zero is acceptable) however, you can use this lazy function:鉴于所有馈送值都是正的(零是可以接受的),但是,您可以使用这个惰性函数:
def product_sum(sum,*args):
return product_sum_intern(sum,0,0,[],*args)
def product_sum_intern(sum,cur_sum,idx,cur,*args):
if idx >= len(args):
if sum == cur_sum:
yield tuple(cur)
elif cur_sum <= sum:
for x in args[idx]:
cur.append(x)
for e in product_sum_intern(sum,cur_sum+x,idx+1,cur,*args):
yield e
cur.pop()
For instance:例如:
>>> list(product_sum(15,[1,12],[1,4,7],[0,3,6,7],[0,1]))
[(1, 7, 6, 1), (1, 7, 7, 0)]
this algorithm gives up on branches as soon as it finds out it is already overshooting the sum.一旦发现它已经超过总和,该算法就会放弃分支。 A more advanced algorithm exists that also gives up branches if there is no way to get in reach of the sum.如果无法达到总和,则存在更高级的算法,该算法也会放弃分支。
To produce a list of all such results:要生成所有此类结果的列表:
combs = [comb for comb in combs if sum(comb) ==1]
Or, if you can use a generator of that data:或者,如果您可以使用该数据的生成器:
combs = (comb for comb in combs if sum(comb) ==1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.