交替附加两个列表中的元素

时间:2016-10-18 10:43:27

标签: python list append

我有三个包含元素的列表:

a = [[0,1],[2,3],...]
b = [[5,6],[7,8],...]

c = []

我想将 a b 中的元素追加到 c 中以获取:

c = [ [0,1],[5,6],[2,3],[7,8],.... ]

7 个答案:

答案 0 :(得分:6)

基本方法:

>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> c = []
>>> for pair in zip(a,b):
...   c.extend(pair)
... 
>>> c
[[0, 1], [5, 6], [2, 3], [7, 8]]
>>> 

如果长度不相等,则会中断。但你可以把这个案子当作一个练习来处理。

答案 1 :(得分:3)

使用字符串切片(以及效率最高)的另一种非常简单的方法:

>>> 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]]

以下是此处提到的答案(Python版本:2.7)与timeit的结果比较:

  1. 使用字符串切片:每个循环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
    
  2. 使用itertools.chain():每个循环1.89 usec

    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
    
  3. 每个循环使用reduce():0.829 usec

    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
    
  4. 使用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
    
  5. 两次使用list.append():每个循环使用1.04

    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
    

答案 2 :(得分:2)

您可以zip两个列表,然后将它们缩减为平面列表:

import operator
c = reduce(operator.concat, zip(a, b))

答案 3 :(得分:2)

假设两个列表的长度相同,最简洁的方法是使用itertools.chainzip

from itertools import chain

a = [[0,1],[2,3],[10,11],[12,13]]
b = [[5,6],[7,8],[15,16],[17,18]]

c = [*chain(*zip(a, b))]
print(c)

<强>输出

[[0, 1], [5, 6], [2, 3], [7, 8], [10, 11], [15, 16], [12, 13], [17, 18]]

正如juanpa.arrivillaga在评论中提到的那样,该语法不适用于旧版本的Python。相反,你可以做

c = list(chain(*zip(a, b)))

这是另一个选项,它不使用导入或* splat运算符:

c = [u for t in zip(a, b) for u in t]

如果您需要处理长度不等的输入列表,请查看Itertools Recipes中的roundrobin函数。例如,

c = list(roundrobin(a, b))

答案 4 :(得分:1)

考虑:

merged = []
for a_element, b_element in zip(a, b):
    merged.append(a_element)
    merged.append(b_element)

除非您有非常严格的性能要求,否则最简单的方法是正确的方法。

答案 5 :(得分:1)

使用实现itertools more_itertools

roundrobin recipe
>>> from more_itertools import roundrobin
>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> list(roundrobin(a, b))
[[0, 1], [5, 6], [2, 3], [7, 8]]

答案 6 :(得分:0)

假设len(a)== len(b)并且你依次逐个添加它们:

for i in range(len(a)):
        c.append(a[i])
        c.append(b[i])

但是,我建议使用c = deque()。因为如果你做了大量的追加,deques会更快。