Re: [問題] 動態產生FOR迴圈的辦法

看板Python作者 (mathfeel)時間14年前 (2011/12/14 06:21), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串7/9 (看更多)
※ 引述《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迴圈寫一百行, 還有什麼比較快的方法呢? 處理任意多個list的方法: #!/usr/bin/env python def list_product(*args): if not args: yield "" else: for ii in args[0]: for jj in list_product(*args[1:]): yield ii + jj l1 = ['a', 'b', 'c'] l2 = ['d', 'e', 'f'] l3 = ['g', 'h', 'i'] print(list(list_product(l1,l2,l3))) 測試: $ python listproduct.py ['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'] -- In heaven, all the interesting people are missing. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 108.66.116.155 ※ 編輯: mathfeel 來自: 108.66.116.155 (12/14 06:23)

12/14 08:22, , 1F
推!
12/14 08:22, 1F

12/17 19:52, , 2F
thx a lot
12/17 19:52, 2F
文章代碼(AID): #1Evy_LgX (Python)
討論串 (同標題文章)
文章代碼(AID): #1Evy_LgX (Python)