如何在python中获取列表元素的所有组合?

时间:2020-05-21 16:16:47

标签: python

假设在Python中有A1,A2,...,An.这样的n个列表,如果A*={x1,x2,...,xn}中的x1A1, x2 is in A2,..., xn中,我们将An命名为这些列表的组合。通过数学,我们知道这些组合的数量为|A1| * |A2|*... * |An|。我该如何在python中编写一个函数来为我执行此操作并返回所有这些组合?

1 个答案:

答案 0 :(得分:1)

您可以使用itertools.product

from itertools import product

a1 = range(0, 3)
a2 = range(3, 6)
a3 = range(6, 9)

print(list(product(a1, a2, a3)))

输出:

[(0, 3, 6), (0, 3, 7), (0, 3, 8), (0, 4, 6), (0, 4, 7), (0, 4, 8), (0, 5, 6), (0, 5, 7), (0, 5, 8), (1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 5, 6), (1, 5, 7), (1, 5, 8), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 5, 6), (2, 5, 7), (2, 5, 8)]