1
xingxiucun 2014-06-16 18:17:42 +08:00 2
reduce(lambda x, y: x + y, zip(a, b))
|
2
tonyluj 2014-06-16 18:18:35 +08:00 1
想到一个(python):
[item for elem in zip([1,2,3],['a','b','c']) for item in elem] |
3
gkiwi OP |
4
phuslu 2014-06-16 18:25:40 +08:00 1
我这个效率比较低,但是稍微短一些
sum(map(list, zip(t, m)), []) |
5
ddzz 2014-06-16 18:29:48 +08:00 via Android 1
第一反应就是循环其中一个数组,然后将他们元素逐个加到一个新的数组,怎么实现不重要,能实现就行
|
8
hanks315 2014-06-16 18:34:03 +08:00
[item for elem in zip(a, b) for item in elem]
|
12
xieranmaya 2014-06-16 18:48:43 +08:00
_.flatten(_.zip([1,2,3],['a','b','c']))
JS的 |
13
xieranmaya 2014-06-16 18:49:06 +08:00
咦,这里好像是py板块...
|
14
hit9 2014-06-16 18:55:33 +08:00 1
来个sum的:
>>> sum(zip(t,m), tuple()) (1, 'a', 2, 'b', 3, 'c') |
15
9hills 2014-06-16 19:15:25 +08:00
1l好评,效率也不错,reduce是迭代调用的
|
16
gkiwi OP @xieranmaya 你乱入了...话说flatten,zip,_,是自带的函数?我查了查也没找到.用什么库了?
|
18
Actrace 2014-06-16 20:43:16 +08:00 1
一行代码是指调用一个函数(指令)还是写成一行?
不管是不是一个函数(指令),又或者纯靠语法,一行实现都没啥问题啊。 |
19
013231 2014-06-16 20:53:18 +08:00 1
@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 2014-06-16 22:25:22 +08:00 1
@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 2014-06-16 22:26:46 +08:00 1
@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 2014-06-17 09:53:06 +08:00
@gkiwi Underscore啊,http://underscorejs.org/
|
25
gkiwi OP @xieranmaya 谢谢.看了下,功能很强大,万能的下划线'_' .
|