zip
与*
和一起使用itertools.chain.from_iterable
。
>>> from itertools import chain, izip
>>> [list(chain.from_iterable(x)) for x in zip(*a)] #or `izip`
[[1, 2, 3, 7, 8, 9, 13, 14, 15], [4, 5, 6, 10, 11, 12, 16, 17, 18]]
这里zip(*a)
返回:
[([1, 2, 3], [7, 8, 9], [13, 14, 15]), ([4, 5, 6], [10, 11, 12], [16, 17, 18])]
现在您可以使用chain.from_iterable(x)
.
时间比较:
In [1]: from itertools import izip, chain
In [2]: a = [[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]], [[13,14,15],[16,17,18]]]
In [3]: %timeit [list(chain.from_iterable(x)) for x in zip(*a)]
100000 loops, best of 3: 3.71 us per loop
In [4]: %timeit [[i for v in r for i in v] for r in zip(*a)]
100000 loops, best of 3: 2.73 us per loop
In [5]: b = a *100
In [6]: %timeit [list(chain.from_iterable(x)) for x in zip(*b)]
10000 loops, best of 3: 97.6 us per loop
In [7]: %timeit [list(chain.from_iterable(x)) for x in izip(*b)]
10000 loops, best of 3: 97.6 us per loop
In [8]: %timeit [[i for v in r for i in v] for r in zip(*b)]
10000 loops, best of 3: 144 us per loop
In [9]: %timeit [[i for v in r for i in v] for r in izip(*b)]
10000 loops, best of 3: 143 us per loop
In [10]: c = a*10000
In [11]: %timeit [list(chain.from_iterable(x)) for x in zip(*c)]
100 loops, best of 3: 12.9 ms per loop
In [12]: %timeit [list(chain.from_iterable(x)) for x in izip(*c)]
100 loops, best of 3: 12.3 ms per loop
In [13]: %timeit [[i for v in r for i in v] for r in zip(*c)]
100 loops, best of 3: 17 ms per loop
In [14]: %timeit [[i for v in r for i in v] for r in izip(*c)]
100 loops, best of 3: 17.1 ms per loop