本文實(shí)例講述了Python列表list排列組合操作。分享給大家供大家參考,具體如下:
排列
例如:
輸入為
['1','2','3']和3
輸出為
['111','112','113','121','122','123','131','132','133','211','212','213','221','222','223','231','232','233','311','312','313','321','322','323','331','332','333']
實(shí)現(xiàn)代碼:
# -*- coding:utf-8 -*-#! pyhton2from itertools import productl = [1, 2, 3]print list(product(l, l))print list(product(l, repeat=3))
上述代碼運(yùn)行輸出:
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
組合
例如:
輸入為
[1, 2, 3]和2
輸出為
[1, 2], [1, 3], [2, 3] 不考慮順序
實(shí)現(xiàn)代碼:
# -*- coding:utf-8 -*-#! pyhton2from itertools import combinationsl = [1, 2, 3, 4, 5]print list(combinations(l, 3))
上述代碼運(yùn)行輸出:
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選