我有三个带有元素的列表:
a = [[0,1],[2,3],...]
b = [[5,6],[7,8],...]
c = []
我想将元素a和b附加到c中以获得:
c = [ [0,1],[5,6],[2,3],[7,8],.... ]
最佳答案
另一种非常简单的使用字符串切片的方法(且性能最高)是:
>>> 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):使用字符串切片:每个循环0.586 usec
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个usecmoin@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 usecmoin@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 usec 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个usecmoin@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