Reputation: 127
I have two lists:
a = [0, 3, 5, 6, 10, 14]
b = [2, 4, 8, 9, 12, 17]
I would like to iterate over both at the same time in alternating steps and deal with the values in increasing order. So if we were printing each value they would be in this order:
0, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 17
I've messed around with it, trying things like:
i = 0
j = 0
while i < len(a) or j < len(b):
if a[i] < b[j]:
print a[i]
i += 1
elif b[j] < a[i]:
print b[j]
j += 1
but this results in a keyerror at the end of one of the lists.
Upvotes: 4
Views: 54
Reputation: 33107
As Andrej commented, you can use heapq.merge
instead:
>>> import heapq
>>> print(*heapq.merge(a, b))
0 2 3 4 5 6 8 9 10 12 14 17
Upvotes: 0
Reputation: 33107
You just need to use and
instead of or
and afterwards print whatever's remaining:
while i < len(a) and j < len(b):
...
k, remaining = (i, a) if i < len(a) else (j, b)
for x in remaining[k:]:
print(x)
Upvotes: 0
Reputation: 14104
I think zip
is what you want
for aa ,bb in zip(a, b):
print(f'{aa},{bb}')
Upvotes: 0