Merge 3 lists into 1 list

前端 未结 4 485
离开以前
离开以前 2020-12-19 19:25

I want to merge 3 lists in to a single list. For example, I have three lists:

a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]

and fina

相关标签:
4条回答
  • 2020-12-19 19:46
    a = [0, 3, 6, 9]
    b = [1, 4, 7, 10]
    c = [2, 5, 8, 11]
    d=[]
    print [j  for i in zip(a,b,c) for j in i]
    

    Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

    0 讨论(0)
  • 2020-12-19 19:49
    import itertools as it
    
    list(it.chain.from_iterable(it.izip(a,b,c)))
    
    0 讨论(0)
  • 2020-12-19 20:01

    Using reduce is another option:

    >>> a = [0, 3, 6, 9]
    b = [1, 4, 7, 10]
    c = [2, 5, 8, 11]
    >>> reduce(lambda x, y: list(x)+list(y), zip(a,b, c))
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    
    0 讨论(0)
  • 2020-12-19 20:08

    You can do it like this:

    a = [0, 3, 6, 9]
    b = [1, 4, 7, 10]
    c = [2, 5, 8, 11]
    merged=a+b+c
    merged.sort()
    

    Since you are adding the list the merged list will contains all values from abc but not in the correct order.That's why I used .sort() to sort the list

    0 讨论(0)
提交回复
热议问题