![](/img/trans.png)
[英]Get the index in order of values from max to min without sorting the output index list and amend another list as well
[英]How can I get the index of max values in list and then print the values from another list with max's index?
d=[1,2,3,4,5,6,7]
g=[1,2,3,100,4,5,100]
m=max(g)
ll=[i for i, j in enumerate(g) if j == m]
print("The longest event time is",m,"for the event(s):",d[*ll])
我需要在事件之后打印 d 列表中的最大值索引這樣,(事件的最長事件時間為 100:4 7
您可以簡單地創建一個 function 來查找列表中的最大值和索引,並在第二個列表中返回相同索引的相應值。 這是代碼:
# creating a function to get the index of Max in list A and return the corresponding value of the same index in list B
def get_id_max(first_list, second_list):
# Finding the max, and then it's index in the first list
global max_value
global max_index
max_value = max(first_list)
max_index = first_list.index(max_value)
# Return the corresponding value in the second list
return second_list[max_index]
# Defining A, B, and C
A = [2011,2012,2013,2014,2015]
B = [50, 60, 15, 76, 55]
C = [1.25, 2.2, 0.5, 1, 15]
print(f"The maximum value is {get_id_max(B,A)} and it's corresponding index is {max_index}")
# The maximum value is 2014 and it's corresponding index is 3
print(f"The maximum value is {get_id_max(C,A)} and it's corresponding index and value are {max_index,max_value}")
# The maximum value is 2015 and it's corresponding index and value are (4, 15)
events = [1, 2, 3, 4, 5, 6, 7]
durations = [1, 2, 3, 100, 4, 5, 100]
max_duration = max(durations)
longest_events = (str(event) for event, duration in zip(events, durations)
if duration == max_duration)
print(f"The longest event time is {max_duration}, for the event(s): {','.join(longest_events)}")
您當前的方法需要在列表中多次通過。 這不是最優化的。
這是一種僅在一次通過中計算最大值的算法。 它類似於最大值的經典手動計算,除了它處理所有最大值以及最大值是在一個列表中計算的事實,但保存的值來自另一個列表(使用zip
)
m = float ('-inf')
out = [] # optional if -inf is not a possible value
for a,b in zip(d,g):
if b>m:
out = [a]
m=b
elif b == m:
out.append(a)
print(out)
Output: [4, 7]
沒有zip
替代方案:
m = float ('-inf')
out = [] # optional if -inf is not a possible value
for i,b in enumerate(g):
if b>m:
out = [d[i]]
m=b
elif b == m:
out.append(d[i])
你可以通過一些列表理解來解決這個問題:
vals = [dat[0] for dat in zip(d, g) if dat[1] == max(g)]
print(f"The longest event times are {max(g)}, for the event(s): {vals}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.