Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

how to define dynamic nested loop python function

a = [1]
b = [2,3]
c = [4,5,6]

d = [a,b,c]


for x0 in d[0]:
    for x1 in d[1]:
        for x2 in d[2]:
            print(x0,x1,x2)

Result:

1 2 4
1 2 5
1 2 6
1 3 4
1 3 5
1 3 6

Perfect, now my question is how to define this to function, considering ofcourse there could be more lists with values. The idea is to get function, which would dynamicaly produce same result.

Is there a way to explain to python: "do 8 nested loops for example"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use itertools to calculate the products for you and can use the * operator to convert your list into arguments for the itertools.product() function.

import itertools

a = [1]
b = [2,3]
c = [4,5,6]

args = [a,b,c]

for combination in itertools.product(*args):
    print combination

Output is

(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...