如何在 Python 中生成列表的所有排列組合?
可以使用 itertools 軟體包排列方法在 Python 中查詢列表的所有排列。您可以如下使用它 −
示例
import itertools perms = list(itertools.permutations([1, 2, 3])) print(perms)
輸出
將給出以下輸出 −
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
廣告
可以使用 itertools 軟體包排列方法在 Python 中查詢列表的所有排列。您可以如下使用它 −
import itertools perms = list(itertools.permutations([1, 2, 3])) print(perms)
將給出以下輸出 −
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]