简体   繁体   中英

Pass a combination of values as function's parameters

i want to pass the parameters as the combination of a,b,c,d values

a = [1,2,3,4,5,6,7,8,9]
b = [5,6,7,8,9,10,11,12,13,14,15]
c = [1,2,3,4,6,12,18]
d = [1,2,3,4,6,12,18,24]
results = []

this is my funcion:

def calc(a,b,c,d):
 ....

i want it to run calc(1,5,1,1) and then calc(1,5,1,2) ... calc(1,5,1,24) , calc(1,5,2,1) ... calc(1,5,2,24) ... calc(1,6,1,1) ... calc(1,6,18,24) ... calc(2,5,1,1) ... calc(2,5,1,24) ... until calc(9,15,18,24)

i want to pass all possible combinations of a,b,c and d as parameters to the function

i have made it by using nested loops

for i in a:
    for j in b:
        for k in c:
             for l in d:
                 results.append(calc(i,j,k,l))

but i think this is not the best solution

it takes 15 min running because the dataset i'm using is too big

To tame the complexity a little bit, you can use itertools.product :

itertools.product(*iterables, repeat=1)

Cartesian product of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as (x,y) for x in A for y in B) .

import itertools

p = itertools.product(a, b, c, d)

for value_a, value_b, value_c, value_d in p:
    result = calc(value_a, value_b, value_c, value_d)

    print(result)

The runtime can't really be changed if you need to evaluate everything - but that would depend on your calc function and whether you have any repeats in your inputs (which would allow you to use dynamic programming and cache lookups to your function instead).

For simplifying iteration, you can use itertools.product :

Cartesian product of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

So to iterate over the product of all these lists:

import itertools

for a_i, b_i, c_i, d_i in itertools.product(a, b, c, d):
    calc(a_i, b_i, c_i, d_i)

However be aware that this might not be the exact same iteration pattern as you mentioned in your example, but it will still iterate over each possible combination from your lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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