避免多层嵌套的for循环可以使用迭代器和递归来解决。下面是几种常见的解决方法:
from itertools import product
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for i, j in product(list1, list2):
print(i, j)
def nested_loop(lists, current_index, current_result):
if current_index == len(lists):
print(current_result)
return
for item in lists[current_index]:
nested_loop(lists, current_index + 1, current_result + [item])
list1 = [1, 2, 3]
list2 = [4, 5, 6]
nested_loop([list1, list2], 0, [])
以上两种方法可以帮助我们避免使用多层嵌套的for循环,提高代码的可读性和效率。
上一篇:避免对自身进行迭代(列表)
下一篇:避免多次编写相同的函数