作者curist (SERIOUSLY!!!???)
看板Python
标题Re: [问题] 动态产生FOR回圈的办法
时间Mon Dec 12 20:27:04 2011
没用itertools的话
def add_up(i, *lists):
return ''.join([list[i] for list in lists])
[add_up(i, listOne, listTwo, listThree) for i in range(len(listOne))]
用ipython timeit测
timeit [add_up(i,listOne,listTwo,listThree) for i in range(len(listOne))]
100000 loops, best of 3: 2.22 us per loop
timeit [''.join(x) for x in itertools.product(listOne, listTwo, listThree)]
100000 loops, best of 3: 5.96 us per loop
※ 引述《suzuke (suzuke)》之铭言:
: import itertools
: listOne = ['a','b','c']
: listTwo = ['d','e','f']
: listThree = ['g','h','i']
: for x in itertools.product(listOne,listTwo,listThree):
: print ''.join(x)
: 根据上一篇的回文, 用itertools就可以解决罗~ 大概是这样, 有错请指正!
: ※ 引述《autumned (autumned)》之铭言:
: : http://docs.python.org/library/itertools.html#itertools.product
: : 有预设的module罗
: : 请参照product
: : 其他很多想要的组合功能也有:-)
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.44.25.16
1F:→ curist:f = lambda x, *args: ''.join(arg[x] for arg in args) 12/12 20:36
2F:→ curist:这样宣告的话速度又跟itertools差不多..不懂.. 12/12 20:36
3F:→ suzuke:不过这样的话, list内的个数不一样就不能做了 12/12 20:58
4F:→ kdjf:itertools是用iterater,保证记忆体不会炸掉 12/13 00:01
5F:→ kdjf: (你如果要把所有的东西放在list里, 好像没差就是了... 12/13 00:02
6F:推 marketcos:谢谢各位提供解答的高手, 在受益良多! 12/13 14:25