目前,我在 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_func2
和 my_combinations
函数定义)作为 list1
中的元素数获取、list2
和 list3
运行到 4-5 位数,现在显然效率低下?
作为一个思考过程,如果我在进入最外层循环之前预先定义了 list1
、list2
和 list3
,itertools.product
可能会有效地为我提供所需的组合.但是,我不认为我可以在这种情况下使用它。