嵌套到 Python 中的动态深度

nesting to a dynamic depth in Python

我正在尝试解决一个问题,该问题需要嵌套的层数与列表中的项目数一样多。或者更准确地说,是列表中的可迭代对象。

def example(arg_list):
for i in arg_list[0]:
    for j in arg_list[1]:
        for k in arg_list[2]:
            print "{} {} {}".format(i,j,k)

只要 "arg_list" 是一个包含 3 个可迭代对象的列表,例如 [[1,3,4],[4,5,6],上面的函数就 运行 没问题, [9,3,2,1,0]]。如果列表中总是有四个可迭代对象,那也很容易做到。我需要弄清楚如何创建一个函数,该函数将为添加到 "arg_list" 参数的每个可迭代对象添加另一个嵌套级别。似乎递归可能是要走的路,但还没有弄清楚。

您要找的是 笛卡尔积。 Python 的 itertools 模块有一个函数可以为您完成。

from itertools import product

def example(arg_list):
    for items in product(*arg_list):
        print " ".join(str(item) for item in items)

你可以使用递归,比如:

def example(arg_list, res=[]):
    if arg_list == []:
        print res
        return
    for i in arg_list[0]:
        example(arg_list[1:], res+[i])