[英]Python: How to loop through a list to find the maximum value with a positive value indexed in another list
我有兩個清單。 我想找到的最大價值list_one
,在使用相同的索引時list_two
,具有正值。 我不想對列表進行排序,因為索引必須保持其完整性。 請參見下面的示例(我現實生活中的問題每個列表有數百個項目,因此必須使用循環):
list_one = [12, 300, 47, 977, 200]
list_two = [-8, 10, 2, -1, 4]
list_one
的最大值為977
,即索引[3]
。 但是如果我們查看list_two
中的相同索引,我們會發現它有一個負值。 下一個最高值是 300,該索引在列表二中確實具有正值。 因此,該算法的預期結果將返回索引1
。 這是我到目前為止所擁有的:
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...
您可以使用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]))
這將返回: (1, 300)
,同時提供您正在尋找的索引和值。
給定不同的列表,您將看到一致的結果:
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.