如何用Python内置迭代工具简化三层嵌套循环生成全组合?
简化三层嵌套循环生成三元组合的Python方法
你需要生成列表所有元素的三元组合,原三层嵌套循环可以用Python标准库itertools里的product工具简化成一行循环,它专门用来生成多个可迭代对象的笛卡尔积,正好匹配你的需求。
原循环代码
some_list = ["AB", "CD", "EF", "GH"] for word_1 in some_list: for word_2 in some_list: for word_3 in some_list: print(word_1, word_2, word_3) # 输出所有可能的三元组合
无效的zip尝试
some_list = ["AB", "CD", "EF", "GH"] for word_1 ,word_2, word_3 in zip(some_list, some_list, some_list): print(word_1 , word_2, word_3) # 仅输出并行元素,不符合需求
解决方案:使用itertools.product
import itertools some_list = ["AB", "CD", "EF", "GH"] # repeat=3表示重复使用some_list三次,等价于传入三次some_list for word_1, word_2, word_3 in itertools.product(some_list, repeat=3): print(word_1, word_2, word_3)
这段代码的输出和原三层嵌套循环完全一致,product会自动遍历所有可能的元素组合,不用手动写多层嵌套。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

