如何简化这些嵌套的for循环? [英] How can I simplify these nested for loops?

查看:472
本文介绍了如何简化这些嵌套的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对此进行简化,以便可以控制有多少嵌套的for循环.本质上是3

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

并且将会是4

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

我几乎是个初学者.

CreateDirectionList仅根据输入的字符串返回一个包含2个字符串的列表

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

推荐答案

使用递归生成器函数可以很容易地做到这一点:

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

您尚未指定CreateDirectionList函数的工作方式,因此这是我的生成器与工厂函数一起工作的示例,该函数从['left','right','up','down']的起始序列中删除了传入的值(这意味着您永远不会得到相同的结果)值连续两次).

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)

输出为:

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

这篇关于如何简化这些嵌套的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆