嵌套循环的更有效方法

时间:2021-02-05 09:47:52

标签: python-3.x nested-loops

目前,我在 python 中有一个嵌套循环,它遍历列表,但可迭代的子列表取决于父循环的选定值。因此,请考虑此嵌套循环的代码片段。

my_combinations = []
list1 = ['foo', 'bar', 'baz']
for l1 in list1:
    list2 = my_func1(l1) # Some user defined function which queries through some dataset
    for l2 in list2:
        list3 = my_func2(l1, l2) # Some other user defined function which queries through some dataset
        for l3 in list3:
            my_combinations.append((l1,l2,l3))

是否有一种有效的方法可以将 my_func1 列表中所有允许的组合(由 my_func2my_combinations 函数定义)作为 list1 中的元素数获取、list2list3 运行到 4-5 位数,现在显然效率低下?

作为一个思考过程,如果我在进入最外层循环之前预先定义了 list1list2list3itertools.product 可能会有效地为我提供所需的组合.但是,我不认为我可以在这种情况下使用它。

0 个答案:

没有答案