如何一行代码实现将两个数组交叉

2014-06-16 18:06:40 +08:00
 gkiwi
t=[1,2,3]
m=['a','b','c']

两数组长度一致;
希望一行代码优雅的将数组一一交叉,得到类似如下结果:

[1,'a',2,'b',3,'c']
4644 次点击
所在节点    Python
25 条回复
chlx
2014-06-16 22:25:22 +08:00
@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
013231
2014-06-16 22:26:46 +08:00
@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}
013231
2014-06-16 22:29:34 +08:00
@chlx 你用的t, m非常小吧.
xieranmaya
2014-06-17 09:53:06 +08:00
gkiwi
2014-06-17 10:39:06 +08:00
@xieranmaya 谢谢.看了下,功能很强大,万能的下划线'_' .

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/117831

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX