You can merge two sorted lists using a stack. In this method, you have to treat each sorted list as a stack. After that, continuously pop the smaller elements from the top of the stack and append the popped item to the list. It will continue to do so until the stack is empty.
Suppose I have a number of lists of pairs (int, str), not necessarily of the same length. The only constraint here is that the lists are sorted in ascending order by their integer parts:
a = [(1, 'a'), (4, 'a'), (6, 'b'), (7, 'c'), (12, 'a')]
b = [(5, 'd'), (10, 'c'), (11,'e')]
c = [(0, 'b'), (3, 'd')]
What I would like to do is to emit the string elements in the order in which their corresponding integer elements occur i.e. in this case:
(0, 'b'), (1, 'a'), (3, 'd'), (4, 'a'), ...
I am wondering if there is an obvious (nice + pythonic) way to do this just using iterators of a
, b
and c
? I've looked at itertools
but can't immediately see how to use the functionality in this case. The lists a
, b
, c
might be very large so I'd like to do this without reading them into memory and then sorting ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With