Re: [問題] 動態產生FOR迴圈的辦法
我的寫法:
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
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 8 之 9 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章