How do I concatenate two lists in Python?

前端 未结 25 1807
时光取名叫无心
时光取名叫无心 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:52

    If you want to merge the two lists in sorted form, you can use the merge function from the heapq library.

    from heapq import merge
    
    a = [1, 2, 4]
    b = [2, 4, 6, 7]
    
    print list(merge(a, b))
    
    0 讨论(0)
  • 2020-11-21 06:53

    You could simply use the + or += operator as follows:

    a = [1, 2, 3]
    b = [4, 5, 6]
    
    c = a + b
    

    Or:

    c = []
    a = [1, 2, 3]
    b = [4, 5, 6]
    
    c += (a + b)
    

    Also, if you want the values in the merged list to be unique you can do:

    c = list(set(a + b))
    
    0 讨论(0)
  • 2020-11-21 06:54

    You can use the + operator to combine them:

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

    Output:

    >>> joinedlist
    [1,2,3,4,5,6]
    
    0 讨论(0)
  • 2020-11-21 06:54

    It's also possible to create a generator that simply iterates over the items in both lists using itertools.chain(). This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

    import itertools
    for item in itertools.chain(listone, listtwo):
        # Do something with each list item
    
    0 讨论(0)
  • 2020-11-21 06:57

    If you need to merge two ordered lists with complicated sorting rules, you might have to roll it yourself like in the following code (using a simple sorting rule for readability :-) ).

    list1 = [1,2,5]
    list2 = [2,3,4]
    newlist = []
    
    while list1 and list2:
        if list1[0] == list2[0]:
            newlist.append(list1.pop(0))
            list2.pop(0)
        elif list1[0] < list2[0]:
            newlist.append(list1.pop(0))
        else:
            newlist.append(list2.pop(0))
    
    if list1:
        newlist.extend(list1)
    if list2:
        newlist.extend(list2)
    
    assert(newlist == [1, 2, 3, 4, 5])
    
    0 讨论(0)
  • 2020-11-21 06:57

    You could use the append() method defined on list objects:

    mergedlist =[]
    for elem in listone:
        mergedlist.append(elem)
    for elem in listtwo:
        mergedlist.append(elem)
    
    0 讨论(0)
提交回复
热议问题