简体   繁体   English

在Python中对多个列表的每个组合求和的最快方法

[英]Fastest way to sum values every combination of multiple lists in Python

I have 5 lists that contain some data: 我有5个包含一些数据的列表:

a = [52, 265, 1, 98, 26]
b = [42, 85, 45, 2, 3, 8, 632]
c = [7, 731, 92, 65, 28, 62]
d = [3, 5, 44, 55]
e = [15, 35, 850, 6, 18, 41]

What I want to do is get the sum of the values of every possible combination, for example: 我想要做的是获取每个可能组合的值的总和,例如:

a[0] + b[0] + c[0] + d[0] + e[0] = **121**
...
a[4] + b[6] + c[5] + d[3] + e[5] = **816**

This needs to be done is the fastest way possible, because in my code the length of these lists is bigger, thus making the calculation of all possibilities extremely time demanding. 这需要以最快的方式完成,因为在我的代码中,这些列表的长度较大,因此所有可能性的计算都非常耗时。

My first idea was using nested for loops, but that's not fast enough. 我的第一个想法是使用嵌套的for循环,但这还不够快。 I imagine some transformations and some magic could be done with NumPy to speed up this process. 我想可以使用NumPy进行一些转换和魔术,以加快此过程。

the fastest way to actually sum all the combinations(you actually want the product, not the combinations) is to generate them and sum them 实际求和所有组合(您真正想要的是产品,而不是组合)的最快方法是生成并求和

print([(x,sum(x)) for x in itertools.product(my_list1,my_list2,my_list3,...)])

but I suspect that the secret is to not check all the products, but instead to intelligently select specific values to narrow your search space 但我怀疑,这个秘密是检查所有的产品,而是智能地选择特定值来缩小搜索空间

You want something like this ? 您想要这样的东西吗?

a = [52, 265, 1, 98, 26]
b = [42, 85, 45, 2, 3, 8, 632]
c = [7, 731, 92, 65, 28, 62]
d = [3, 5, 44, 55]
e = [15, 35, 850, 6, 18, 41]

import itertools

print(list(map(lambda x:sum(x),itertools.product(a,b,c,d,e))))

output: 输出:

119, 139, 954, 110, 122, 145, 121, 141, 956, 112, 124, 147, 160, 180, 995, 151, 163, 186, 171, 191, 1006, 162, 174, 197, 843, 863, 1678, 834, 846, 869, 845, 865, 1680, 836, 848, 871, 884, 904, 1719, 875, 887, 910, 895, 915, 1730, 886, 898, 921, 204, 224, 1039, 195, 207, 230, 206, 226, 1041, 197, 209, 232, 245, 265, 1080, 236, 248, 271, 256, 276, 1091, 247, 259, 282, 177, 197, 1012, 168, 180, 203, 179, 199, 1014, 170, 182, 205, 218, 238, 1053, 209, 221, 244, 229, ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM