注意
:此答案是针对上面提出的特定问题的。如果您来自Google,只是想寻找一种使用Python获得笛卡尔积的方法,
itertools.product或者您可能正在寻找简单的列表理解方法-
请参见其他答案。
假设
len(list1) >=len(list2)。然后,你似乎需要的是采取长的所有排列
len(list2)的
list1,并与列表2项匹配。在python中:
import itertoolslist1=['a','b','c']list2=[1,2][list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]
退货
[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]


