
1 xingxiucun Jun 16, 2014 reduce(lambda x, y: x + y, zip(a, b)) |
2 tonyluj Jun 16, 2014 想到一个(python): [item for elem in zip([1,2,3],['a','b','c']) for item in elem] |
3 gkiwi OP |
4 phuslu Jun 16, 2014 我这个效率比较低,但是稍微短一些 sum(map(list, zip(t, m)), []) |
5 ddzz Jun 16, 2014 via Android 第一反应就是循环其中一个数组,然后将他们元素逐个加到一个新的数组,怎么实现不重要,能实现就行 |
8 hanks315 Jun 16, 2014 [item for elem in zip(a, b) for item in elem] |
12 xieranmaya Jun 16, 2014 _.flatten(_.zip([1,2,3],['a','b','c'])) JS的 |
13 xieranmaya Jun 16, 2014 咦,这里好像是py板块... |
14 hit9 Jun 16, 2014 来个sum的: >>> sum(zip(t,m), tuple()) (1, 'a', 2, 'b', 3, 'c') |
15 9hills Jun 16, 2014 1l好评,效率也不错,reduce是迭代调用的 |
16 gkiwi OP @xieranmaya 你乱入了...话说flatten,zip,_,是自带的函数?我查了查也没找到.用什么库了? |
18 Actrace Jun 16, 2014 一行代码是指调用一个函数(指令)还是写成一行? 不管是不是一个函数(指令),又或者纯靠语法,一行实现都没啥问题啊。 |
19 013231 Jun 16, 2014 @xingxiucun @9hills 使用中的itertools.chain, 效率高很多. In [690]: a = range(1000) In [691]: b = range(1000) In [692]: timeit reduce(lambda x, y: x + y, zip(a, b)) 100 loops, best of 3: 3.25 ms per loop In [693]: timeit list(itertools.chain(*zip(x, y))) 10000 loops, best of 3: 110 s per loop |
21 chlx Jun 16, 2014 @013231 我的机子上的结果. In [18]: timeit list(itertools.chain(*zip(t,m))) 1000000 loops, best of 3: 773 ns per loop In [19]: timeit reduce(lambda x, y: x + y, zip(t, m)) 1000000 loops, best of 3: 549 ns per loop |
22 013231 Jun 16, 2014 @9hills 如此. In [719]: a = range(100000) In [720]: b = range(100000) In [721]: cProfile.run('reduce(lambda x, y: x + y, zip(a, b))') 100003 function calls in 46.933 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 99999 27.569 0.000 27.569 0.000 <string>:1(<lambda>) 1 0.005 0.005 46.933 46.933 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 19.341 19.341 46.911 46.911 {reduce} 1 0.017 0.017 0.017 0.017 {zip} In [722]: cProfile.run('list(itertools.chain(*zip(a, b)))') 3 function calls in 0.022 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.014 0.014 0.022 0.022 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.008 0.008 0.008 0.008 {zip} |
24 xieranmaya Jun 17, 2014 @gkiwi Underscore啊,http://underscorejs.org/ |
25 gkiwi OP @xieranmaya 谢谢.看了下,功能很强大,万能的下划线'_' . |