How can I simplify these nested for loops?

天大地大妈咪最大 提交于 2020-04-18 03:51:11

问题


I would like to make this simplified so that I can control how many nested for loops there are. Essentially this would be 3

for d1 in ['left','right','up','down']:
    for d2 in CreateDirectionList(d1):
        for d3 in CreateDirectionList(d2):
            #Do something with list [d1, d2, d3]
return False

and 4 would be

for d1 in ['left','right','up','down']:
    for d2 in CreateDirectionList(d1):
        for d3 in CreateDirectionList(d2):
            for d4 in CreateDirectionList(d3):
                #Do something with list [d1, d2, d3, d4]
return False

I am pretty much a beginner.

CreateDirectionList just returns a list with 2 strings based on a string input


回答1:


You could pretty easily do this with a recursive generator function:

def gen(values, value_list_factory, depth):
    if depth == 0: # base case
        yield ()
        return

    for x in values:
        for rest in gen(value_list_factory(x), value_list_factory, depth-1):  # recurse!
            yield x, *rest

You've not specified how your CreateDirectionList function works, so here's an example of my generator working with a factory function that removes the passed in value from the starting sequence of ['left','right','up','down'] (this means you never get the same value twice in a row).

directions = ['left','right','up','down']

def create(dir):
    return [x for x in directions if x != dir]

for d1, d2, d3 in gen(directions, create, 3):
    print(d1, d2, d3)

The output is:

left right left
left right up
left right down
left up left
left up right
left up down
left down left
left down right
left down up
right left right
right left up
right left down
right up left
right up right
right up down
right down left
right down right
right down up
up left right
up left up
up left down
up right left
up right up
up right down
up down left
up down right
up down up
down left right
down left up
down left down
down right left
down right up
down right down
down up left
down up right
down up down



回答2:


yeah recursion is your friend.

def CreateDirectionList(d):
    if d == "left" or d == "right":
        return ['up','down']
    if d == "up" or d == "down":
        return ['left','right']

def nMoreSteps(d,n):
    if n == 0:
        return [[d]]
    else:
        results = []
        for k in CreateDirectionList(d):
            for k2 in nMoreSteps(k,n-1):
                results.append([d]+k2)
        return results

def nSteps(n):
    results = []
    for d1 in ['left','right','up','down']:
        results += nMoreSteps(d1,n-1)
    return(results)

for k in nSteps(4):
    print(k)


来源:https://stackoverflow.com/questions/60859007/how-can-i-simplify-these-nested-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!