• slider image 221
:::

3-1 排列、組合 itertools 模組

itertools模組,使得排列組合的實現非常簡單:

import itertools 

有序排列:e.g., 4個數內選2個排列:
複製程式碼 程式碼如下:
>>> print( list(itertools.permutations([1,2,3,4],2)) )
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

無序組合:e.g.,4個數內選2個:
複製程式碼 程式碼如下:
>>> print( list(itertools.combinations([1,2,3,4],2))  )
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


Google網站翻譯工具列

站內搜尋