作者KSJ (阿真)
看板Python
标题Re: [问题] 动态产生FOR回圈的办法
时间Mon Dec 12 16:56:39 2011
这个很像 乘法的分配律
a x b x c = (a x b) x c = d x c = result
先做a x b = d
再做d x c = result
所以n个也没问题了
这样的计算类似kron
但是是加法
所以得先自己写一个函式用(与你的想法相同)
def string_add( str_list1, str_list2 ):
result = []
for i in str_list1:
for j in str_list2:
result.append( i + j )
return result
所以假设有100个list
只要将它们放入list群里
list_s = [ list_one, list_two, ..., list_100 ]
list_result = list_s[0]
for list_i in list_s[1:]:
list_result = string_add( list_result, list_i )
print list_result
结果应该一样 速度上也差不多(的慢...)
只有程式码的reuse与想法上有点差别
先求有 再求好吧~
以上
有误请指正 有更好的方法也请分享:)
※ 引述《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: 180.176.140.46
1F:推 marketcos:非常谢谢!!! 12/12 17:23