Re: [問題] 動態產生FOR迴圈的辦法
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
推
12/12 19:42, , 1F
12/12 19:42, 1F
推
12/12 20:17, , 2F
12/12 20:17, 2F
→
12/12 20:17, , 3F
12/12 20:17, 3F
→
12/12 20:21, , 4F
12/12 20:21, 4F
→
12/12 20:22, , 5F
12/12 20:22, 5F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章