Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two sorted python lists [duplicate]

I'm trying to merge two user inputted lists that have been sorted in descending order. I understand how to merge two lists then sort, however i'm struggling the other way around.

# user list input
a = [int(x) for x in input("List 1: ").split()]
b = [int(y) for y in input("List 2: ").split()]

a.sort(reverse=True)
b.sort(reverse=True)

print(a + b)

For example, I want to input: [1, 3, 3, 6] & [1, 4, 5], and my output be: [6, 5, 4, 3, 3, 1, 1]


2 Answers

You can use heapq.merge for this. It takes multiple sorted iterables and merges them into a single sorted output, so:

c = list(heapq.merge(
    sorted(a, reverse=True),
    sorted(b, reverse=True),
    reverse=True)

Note that this works also with iterables (e.g. lazily-calculated, potentially consumable objects), which is when you are more likely to use it (when combining sorted iterables).

I am assuming you get the lists pre-sorted or you just want to know how to do this, since it would probably be preferable to merge the lists first and then sort them (either with sorted or mutating them with .sort()).

like image 177
Paul Avatar answered Sep 20 '25 22:09

Paul


I suggest using sorted().

# user list input
a = [int(x) for x in input("List 1: ").split()]
b = [int(y) for y in input("List 2: ").split()]
print(sorted(a+b,reverse=True))

inp/out

List 1: 1 2 3 
List 2: 1 2 3
[3, 3, 2, 2, 1, 1]
like image 35
Thavas Antonio Avatar answered Sep 21 '25 00:09

Thavas Antonio