作者mathfeel (mathfeel)
看板Python
标题Re: [问题] 动态产生FOR回圈的办法
时间Wed Dec 14 06:21:06 2011
※ 引述《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回圈写一百行, 还有什麽比较快的方法呢?
处理任意多个list的方法:
#!/usr/bin/env python
def list_product(*args):
if not args:
yield ""
else:
for ii in args[0]:
for jj in list_product(*args[1:]):
yield ii + jj
l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l3 = ['g', 'h', 'i']
print(list(list_product(l1,l2,l3)))
测试:
$ python listproduct.py
['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']
--
In heaven, all the interesting people are missing.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 108.66.116.155
※ 编辑: mathfeel 来自: 108.66.116.155 (12/14 06:23)
1F:推 suzuke:推! 12/14 08:22
2F:推 marketcos:thx a lot 12/17 19:52