简体   繁体   English

Python:如何遍历列表以找到另一个列表中索引为正值的最大值

[英]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.我想找到的最大价值list_one ,在使用相同的索引时list_two ,具有正值。 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] . list_one的最大值为977 ,即索引[3] But if we look at the same index in list_two we see it has a negative value.但是如果我们查看list_two中的相同索引,我们会发现它有一个负值。 The next highest value is 300, and that index does have a positive value in list two.下一个最高值是 300,该索引在列表二中确实具有正值。 So the desired outcome of this algorithm would return an index of 1 .因此,该算法的预期结果将返回索引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您可以使用enumerate(list_one)的最大值来测试list_two的值是否为正

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.这将返回: (1, 300) ,同时提供您正在寻找的索引和值。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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