如何在 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)]