-
手掌心
您可以使用该功能product():from itertools import productlist(product(colors, numbers, material + names))
-
一只甜甜圈
使用product, 以及chain名称和材料:from itertools import chain, productcolors = ["blue", "yellow", "green", "black", "magenta"]numbers = [1,2,3,4,5,6,7,8]material = ["beton", "wood", "stone"]names = ["Susi", "Klara", "Claire", "Moni"]out = product(colors, numbers, chain(material, names))部分输出:for i in range(10): print(next(out))('blue', 1, 'beton')('blue', 1, 'wood')('blue', 1, 'stone')('blue', 1, 'Susi')('blue', 1, 'Klara')('blue', 1, 'Claire')('blue', 1, 'Moni')('blue', 2, 'beton')('blue', 2, 'wood')('blue', 2, 'stone')
-
绝地无双
这会起作用,产生 436 种组合:import itertools as itlscolors = ["blue", "yellow", "green", "black", "magenta"]numbers = [1,2,3,4,5,6,7,8]material = ["beton", "wood", "stone"]names = ["Susi", "Klara", "Claire", "Moni"]my_lists = [colors, numbers, material, names]my_combos = [(x,y,z) for (lst_1,lst_2,lst_3) in itls.combinations(my_lists,3) for (x,y,z) in itls.product(lst_1, lst_2, lst_3) ]# print (my_combos)print (len(my_combos))解释:所需的结果被构造为一个列表,并分配给my_combos。该列表是使用具有嵌套双迭代的列表推导式构建的。在嵌套双迭代中:外部 for 循环for (lst_1,lst_2,lst_3) in itls.combinations(my_lists,3)遍历列表的所有可能组合,一次获取 3 个列表。内部 for 循环for (x,y,z) in itls.product(lst_1, lst_2, lst_3)迭代lst_1, lst_2, and的笛卡尔积lst_3(这些lst_1, lst_2, 和lst_3get 为外部 for 循环的每次迭代定义)验证结果中没有重复的代码:# Code to verify that there are no duplicates.from collections import Counterfor x, count_x in counts.items(): if (count_x > 1): # if duplicate print ("Duplicate item ({}) occurs {} times".format(x, count_x))