简体   繁体   中英

Python: How to loop through a list to find the maximum value with a positive value indexed in another list

I have two lists. I'd like to find the largest value in list_one that, when using the same index in list_two , has a positive value. I do not want to sort the lists as the indices must maintain their integrity. See example below (my real life problem has hundreds of items per list so a loop must be used):

list_one = [12, 300, 47, 977, 200]
list_two = [-8, 10, 2, -1, 4]

The max value in list_one is 977 , which is index [3] . But if we look at the same index in list_two we see it has a negative value. The next highest value is 300, and that index does have a positive value in list two. So the desired outcome of this algorithm would return an index of 1 . Here is what I have so far:

max_value = 0
max_index = 0
counter = 0

for value in list_one:
    if value > max_value:
       max_value = value
       max_index = counter
    counter = counter + 1

if list_two[max_index] > 0:
    return max_index
else:
    # Code needed to find 2nd largest value in list one, and so on...
       

You can take the max of enumerate(list_one) with a key that tests of list_two 's value is positive

list_one = [12, 300, 47, 977, 200]
list_two = [-1, 1, 1, -1, 1]

max(enumerate(list_one), key=lambda t: (list_two[t[0]] > 0, t[1]))

This will return: (1, 300) , giving both the index and value you are are looking for.

Given a different list you will see a consistent result:

list_one = [12, 300, 47, 977, 500]
list_two = [-1, 1, 1, -1, 1]

max(enumerate(list_one), key=lambda t: (list_two[t[0]] > 0, t[1]))
# (4, 500)

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