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

看板Python作者 (cablin)時間14年前 (2011/12/18 03:03), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串8/9 (看更多)
我的寫法: def product(lists): indices = range(len(lists)) iters = [iter(l) for l in lists] values = [next(i) for i in iters] while True: yield values for i in indices: try: values[i] = next(iters[i]) break except StopIteration: iters[i] = iter(lists[i]) values[i] = next(iters[i]) else: break >>> L (['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']) >>> [''.join(s) for s in product(L)] ['adg', 'bdg', 'cdg', 'aeg', 'beg', 'ceg', 'afg', 'bfg', 'cfg', 'adh', 'bdh', 'cdh', 'aeh', 'beh', 'ceh', 'afh', 'bfh', 'cfh', 'adi', 'bdi', 'cdi', 'aei', 'bei', 'cei', 'afi', 'bfi', 'cfi'] 程式新手,請多指教<(_ _)> -- 「死ぬのっていや? 殺されたくない?」 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.236.23
文章代碼(AID): #1ExEUGh_ (Python)
討論串 (同標題文章)
文章代碼(AID): #1ExEUGh_ (Python)