看板 Python 關於我們 聯絡資訊
import itertools listOne = ['a','b','c'] listTwo = ['d','e','f'] listThree = ['g','h','i'] for x in itertools.product(listOne,listTwo,listThree): print ''.join(x) 根據上一篇的回文, 用itertools就可以解決囉~ 大概是這樣, 有錯請指正! ※ 引述《autumned (autumned)》之銘言: : http://docs.python.org/library/itertools.html#itertools.product : 有預設的module囉 : 請參照product : 其他很多想要的組合功能也有:-) : ※ 引述《marketcos (marketcos)》之銘言: : : 本身PYTHON初學者 : : 這個問題 我想了兩天了 : : 怎麼寫都很遜, 煩請高手來指點 : : 事情是這樣的... : : 我想把數個lists的元素組合起來 : : 例如: : : # listOne,listTwo,listThree分別是 ['a','b','c'] ['d','e','f'] ['g','h','i'] : : tmp = "" : : combination = [] : : for i in listOne: : : for j in listTwo: : : for k in listThree: : : tmp = i + j + k : : combination.append(tmp) : : print combination : : 執行結果會是 : : ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', : : 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', : : 'ceh', 'cei', 'cfg', 'cfh', 'cfi'] : : 我的問題是,如果今天我的lists不只三個 (可能會有100個) : : 除了for迴圈寫一百行, 還有什麼比較快的方法呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.193.94.21
marketcos:強大!!! 12/12 19:42
KSJ:推一個:) 不過new in version 2.6 Q_Q 12/12 20:17
KSJ:2.5的話 要from future import 什麼嗎? 12/12 20:17
suzuke:應該不用itertools python2.4就有了 12/12 20:21
suzuke:剛剛測試的結果好像是沒product 12/12 20:22