我正在寻找一种简单的方法来解决这个问题。 假设我有一个列表列表,其中列表中的列表数量不确定:
lists = [
[[1,2,3,4],[2,3,4,5]],
[[1,2,3,4],[2,3,4,5],[3,4,5,6]],
[[1,2,3,4]],
[[1,2,3,4],[2,3,4,5]]
]
我现在无法弄清楚是如何生成所有可能组合的排列,同时保持第一级lists
的顺序相同。我已经搞乱了嵌套的for
循环和any()
函数,但收效甚微。嵌套for循环不起作用,因为实际上len(lists)
要大得多,并且需要len(lists)
个for
个循环。有没有人有任何想法?
在上面的例子中,一些可能的排列是:
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]]
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[2,3,4,5]]
[[2,3,4,5],
[1,2,3,4],
[1,2,3,4],
[2,3,4,5]]
[[2,3,4,5],
[3,4,5,6],
[1,2,3,4],
[2,3,4,5]]
答案 0 :(得分:1)
正如@DSM建议的那样,您可能正在寻找笛卡儿产品。排列意味着不同的东西。
>>> import pprint, itertools as it
>>> lists = [
... [[1,2,3,4],[2,3,4,5]],
... [[1,2,3,4],[2,3,4,5],[3,4,5,6]],
... [[1,2,3,4]],
... [[1,2,3,4],[2,3,4,5]]
... ]
>>> pprint.pprint(list(it.product(*lists)))
[([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]),
([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]),
([1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4]),
([1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5]),
([1, 2, 3, 4], [3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]),
([1, 2, 3, 4], [3, 4, 5, 6], [1, 2, 3, 4], [2, 3, 4, 5]),
([2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]),
([2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]),
([2, 3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4]),
([2, 3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5]),
([2, 3, 4, 5], [3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]),
([2, 3, 4, 5], [3, 4, 5, 6], [1, 2, 3, 4], [2, 3, 4, 5])]