How do I concatenate two lists in Python?

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

提交回复
热议问题