I need to iterate on two lists in the following way:
Pseudo code:
j=1
for i=1 to n:
print a[i], b[j]
while b[j+1] <= a[i]:
j++
print a[i], b[j]
For example:
a = [1 3 5 7]
b = [2 4 9]
Desired output:
1 2
3 2
5 2
5 4
7 4
How do you do it cleanly in python?
Your pseudo code will almost work in Python. Some working code that does what you want is:
Note the few changes to make it work in Python:
iandjshould start there.len(a)returns the length ofa(4 in this case), and iteratingithroughrange(len(a))executes the loop for each integer from0tolen(a)-1, which is all of the indices ina.++operation is not supported in Python, so we usej +=1instead.b, so we test to make surejwill be in bounds before incrementing it.This code can be made more pythonic by iterating through the list as follows:
In general, you probably don’t want to just print list elements, so for a more general use case you can create a generator, like:
And then you can print them as before with