作者doglegbow (堡)
看板Python
标题Re: [问题] 动态产生FOR回圈的办法
时间Mon Dec 12 16:57:21 2011
我会想用回圈跟函式去做
以下是做法
不过不保证速度
def multiply(lista,listb):#将两list结合
comb_list=[]
for a in lista:
for b in listb:
comb_list.append(a+b)
return comb_list
list1=['a','b','c']
list2=['d','e','f']
list3=['g','h','i']
all_list=[list1,list2,list3]#将所有list放在一list
temp=['']
for n in all_list:
temp=multiply(temp,n)
print temp
※ 引述《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回圈写一百行, 还有什麽比较快的方法呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 211.75.163.227
1F:→ marketcos:真的很谢谢!!! 12/12 17:23
2F:→ marketcos:我是要推文, 不知为何变加注的方式... 12/12 17:23
3F:推 marketcos:推回来 12/12 17:26