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

看板Python作者 (SERIOUSLY!!!???)時間14年前 (2011/12/12 20:27), 編輯推噓1(105)
留言6則, 4人參與, 最新討論串6/9 (看更多)
沒用itertools的話 def add_up(i, *lists): return ''.join([list[i] for list in lists]) [add_up(i, listOne, listTwo, listThree) for i in range(len(listOne))] 用ipython timeit測 timeit [add_up(i,listOne,listTwo,listThree) for i in range(len(listOne))] 100000 loops, best of 3: 2.22 us per loop timeit [''.join(x) for x in itertools.product(listOne, listTwo, listThree)] 100000 loops, best of 3: 5.96 us per loop ※ 引述《suzuke (suzuke)》之銘言: : 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 : : 其他很多想要的組合功能也有:-) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.44.25.16

12/12 20:36, , 1F
f = lambda x, *args: ''.join(arg[x] for arg in args)
12/12 20:36, 1F

12/12 20:36, , 2F
這樣宣告的話速度又跟itertools差不多..不懂..
12/12 20:36, 2F

12/12 20:58, , 3F
不過這樣的話, list內的個數不一樣就不能做了
12/12 20:58, 3F

12/13 00:01, , 4F
itertools是用iterater,保證記憶體不會炸掉
12/13 00:01, 4F

12/13 00:02, , 5F
(你如果要把所有的東西放在list裡, 好像沒差就是了...
12/13 00:02, 5F

12/13 14:25, , 6F
謝謝各位提供解答的高手, 在受益良多!
12/13 14:25, 6F
文章代碼(AID): #1EvVCQUP (Python)
討論串 (同標題文章)
文章代碼(AID): #1EvVCQUP (Python)