天天看點

Python 排列 組合 | itertools.permutations() itertools.combinations()

從一個清單中取N個元素,有多少種取法

排列:itertools.permutations(List, N) #124 != 421

組合:itertools.combinations(List, N) #124 = 421

import itertools
print(list(itertools.permutations([1,2,3,4],3)))
# [(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]
           

繼續閱讀