Search code examples
pythonfor-loopparallel-processingjoblib

How can I turn two for loops into one so that joblib can be used?


func is a complex function.

I have two for loops, how can I turn two for loops into one so that joblib can be used?

Code show as below:

def func(a, b):
    print(a, b)


s1 = range(4)
d2 = range(5)
for s in s1:
    for d in d2:
        func(s, d)


Solution

  • I have two for loops, how can I turn two for loops into one so that joblib can be used?

    You can "merge" multiple loops into a single one by combining the iterators using the itertools module.

    from itertools import product
    s1 = range(4)
    d2 = range(5)
    for i in product(s1, d2):
       # i is know equivalent to your (s, d)
       print(i)