Interleave multiple lists of the same length in Python

后端 未结 9 1629
刺人心
刺人心 2020-11-22 10:11

In Python, is there a good way to interleave two lists of the same length?

Say I\'m given [1,2,3] and [10,20,30]. I\'d like to transform th

9条回答
  •  甜味超标
    2020-11-22 10:43

    I like aix's solution best. here is another way I think should work in 2.2:

    >>> x=range(3)
    >>> x
    [0, 1, 2]
    >>> y=range(7,10)
    >>> y
    [7, 8, 9]
    >>> sum(zip(x,y),[])
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate list (not "tuple") to list
    >>> sum(map(list,zip(x,y)),[])
    [0, 7, 1, 8, 2, 9]
    

    and one more way:

    >>> a=[x,y]
    >>> [a[i][j] for j in range(3) for i in (0,1)]
    [0, 7, 1, 8, 2, 9]
    

    and:

    >>> sum((list(i) for i in zip(x,y)),[])
    [0, 7, 1, 8, 2, 9]
    

提交回复
热议问题