作者curist (SERIOUSLY!!!???)
看板Python
標題Re: [問題] 動態產生FOR迴圈的辦法
時間Mon Dec 12 20:27:04 2011
沒用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
→ curist:f = lambda x, *args: ''.join(arg[x] for arg in args) 12/12 20:36
→ curist:這樣宣告的話速度又跟itertools差不多..不懂.. 12/12 20:36
→ suzuke:不過這樣的話, list內的個數不一樣就不能做了 12/12 20:58
→ kdjf:itertools是用iterater,保證記憶體不會炸掉 12/13 00:01
→ kdjf: (你如果要把所有的東西放在list裡, 好像沒差就是了... 12/13 00:02
推 marketcos:謝謝各位提供解答的高手, 在受益良多! 12/13 14:25