简体   繁体   中英

Iterate over two lists while i-1 condition is met in python

I have two lists which I want to iterate through in a pairwise way to select pairs that meet my condition

list1 = [0, 6, 22, 29]
list2 = [3, 38, 48]

I iterate through them using zip :

for i, j in list(zip(list1, list2)):
  print(i, j)

This returns

0  3
6  38
22 48

This works fine but I want to build in the following condition: The pair should only be returned if the first value ( i ) of a pair is larger than the last value ( j ) of the previous pair.

In this case, the first two pairs are correct, but the third is not since 22 is contained in 6:48 .

How can I build this logic into my loop?

First of all, you do not need to cast your zip() to a list() , as you are just iterating trough it.

Then, you can add a third list to the zip() which can be used to do the comparison. You can slice list1 and list2 because there is no "last j value of the previous pair" to compare with.

The third argument, list2 will be used to check the condition. During the iteration, its element k is "one index late", so it is equal to the last j encountered.

for i, j, k in zip(list1[1:], list2[1:], list2):
    if i > k:
        print(i, j)

If you need to include the first pair, you can use this nice trick found by @schwobaseggl :

for i, j, k in zip(list1, list2, [-1] + list2):
    if i > k:
        print(i, j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM