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

看板Python作者 (堡)時間14年前 (2011/12/12 16:57), 編輯推噓1(102)
留言3則, 1人參與, 最新討論串3/9 (看更多)
我會想用迴圈跟函式去做 以下是做法 不過不保證速度 def multiply(lista,listb):#將兩list結合 comb_list=[] for a in lista: for b in listb: comb_list.append(a+b) return comb_list list1=['a','b','c'] list2=['d','e','f'] list3=['g','h','i'] all_list=[list1,list2,list3]#將所有list放在一list temp=[''] for n in all_list: temp=multiply(temp,n) print temp ※ 引述《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: 211.75.163.227

12/12 17:23, , 1F
真的很謝謝!!!
12/12 17:23, 1F

12/12 17:23, , 2F
我是要推文, 不知為何變加註的方式...
12/12 17:23, 2F

12/12 17:26, , 3F
推回來
12/12 17:26, 3F
文章代碼(AID): #1EvS7rYI (Python)
討論串 (同標題文章)
文章代碼(AID): #1EvS7rYI (Python)