How do I concatenate two lists in Python?

前端 未结 25 1806
时光取名叫无心
时光取名叫无心 2020-11-21 06:18

How do I concatenate two lists in Python?

Example:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

Expected outcome:

>&g         


        
相关标签:
25条回答
  • 2020-11-21 06:59
    list(set(listone) | set(listtwo))
    

    The above code, does not preserve order, removes duplicate from each list (but not from the concatenated list)

    0 讨论(0)
  • 2020-11-21 07:00

    With Python 3.3+ you can use yield from:

    listone = [1,2,3]
    listtwo = [4,5,6]
    
    def merge(l1, l2):
        yield from l1
        yield from l2
    
    >>> list(merge(listone, listtwo))
    [1, 2, 3, 4, 5, 6]
    

    Or, if you want to support an arbitrary number of iterators:

    def merge(*iters):
        for it in iters:
            yield from it
    
    >>> list(merge(listone, listtwo, 'abcd', [20, 21, 22]))
    [1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 20, 21, 22]
    
    0 讨论(0)
  • 2020-11-21 07:01

    It's worth noting that the itertools.chain function accepts variable number of arguments:

    >>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
    >>> [i for i in itertools.chain(l1, l2)]
    ['a', 'b', 'c']
    >>> [i for i in itertools.chain(l1, l2, l3)]
    ['a', 'b', 'c', 'd', 'e', 'f']
    

    If an iterable (tuple, list, generator, etc.) is the input, the from_iterable class method may be used:

    >>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
    >>> [i for i in itertools.chain.from_iterable(il)]
    ['a', 'b', 'c', 'd', 'e', 'f']
    
    0 讨论(0)
  • 2020-11-21 07:03

    You could also use the list.extend() method in order to add a list to the end of another one:

    listone = [1,2,3]
    listtwo = [4,5,6]
    
    listone.extend(listtwo)
    

    If you want to keep the original list intact, you can create a new list object, and extend both lists to it:

    mergedlist = []
    mergedlist.extend(listone)
    mergedlist.extend(listtwo)
    
    0 讨论(0)
  • 2020-11-21 07:03

    If you are using NumPy, you can concatenate two arrays of compatible dimensions with this command:

    numpy.concatenate([a,b])
    
    0 讨论(0)
  • 2020-11-21 07:04
    import itertools
    
    A = list(zip([1,3,5,7,9],[2,4,6,8,10]))
    B = [1,3,5,7,9]+[2,4,6,8,10]
    C = list(set([1,3,5,7,9] + [2,4,6,8,10]))
    
    D = [1,3,5,7,9]
    D.append([2,4,6,8,10])
    
    E = [1,3,5,7,9]
    E.extend([2,4,6,8,10])
    
    F = []
    for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):
        F.append(a)
    
    
    print ("A: " + str(A))
    print ("B: " + str(B))
    print ("C: " + str(C))
    print ("D: " + str(D))
    print ("E: " + str(E))
    print ("F: " + str(F))
    

    Output:

    A: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
    B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
    C: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    D: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
    E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
    F: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
    
    0 讨论(0)
提交回复
热议问题