交替追加两个列表中的元素 [英] alternately appending elements from two lists
问题描述
我有三个包含元素的列表:
I have three lists with elements :
a = [[0,1],[2,3],...]
b = [[5,6],[7,8],...]
c = []
我想将 a 和 b 中的元素附加到 c 中以获得:
I want to append elements from a and b into c to get:
c = [ [0,1],[5,6],[2,3],[7,8],.... ]
推荐答案
另一种非常简单的方法字符串切片(也是最高效的),具体如下:
Another very simple approach using string slicing (and most performance efficient) as:
>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> c = a + b # create a list with size = len(a) + len(b)
>>> c[::2], c[1::2] = a, b # alternately insert the value
>>> c
[[0, 1], [5, 6], [2, 3], [7, 8]]
以下是结果与 timeit
的比较,此处提到的答案(Python版本:2.7):
Below is the comparison of results with timeit
for the answers mentioned here (Python version: 2.7):
-
使用字符串切片:每个循环0.586 usec
Using string slicing: 0.586 usec per loop
moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = a + b; c[::2], c[1::2] = a, b"
1000000 loops, best of 3: 0.586 usec per loop
使用 itertools.chain()
:每个循环1.89个
Using itertools.chain()
: 1.89 usec per loop
moin@moin-pc:~$ python -m "timeit" -s "from itertools import chain; a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = list(chain(*zip(a, b)))"
1000000 loops, best of 3: 1.89 usec per loop
使用 reduce()
:每个循环0.829 usc
Using reduce()
: 0.829 usec per loop
moin@moin-pc:~$ python -m "timeit" -s "import operator; a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = reduce(operator.concat, zip(a, b))"
1000000 loops, best of 3: 0.829 usec per loop
使用 list.extend()
:每个循环0.824 usc
Using list.extend()
: 0.824 usec per loop
moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]]; c=[]" "for pair in zip(a,b): c.extend(pair)"
1000000 loops, best of 3: 0.824 usec per loop
使用 list.append()
两次:每个循环1.04 usc
Using list.append()
twice: 1.04 usec per loop
moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]]; c=[]" "for a_element, b_element in zip(a, b): c.append(a_element); c.append(b_element)"
1000000 loops, best of 3: 1.04 usec per loop
这篇关于交替追加两个列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!