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
uj5u.com熱心網友回復:
您可以簡單地創建一個函式來查找串列中的最大值和最大值的索引,并在第二個串列中回傳相同索引的相應值。這是代碼:
# 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)
uj5u.com熱心網友回復:
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)}")
uj5u.com熱心網友回復:
您當前的方法需要多次通過串列。這不是最理想的。
這是一種僅通過一次計算最大值的演算法。它類似于最大值的經典手動計算,除了它處理所有最大值以及最大值計算一個串列的事實,但保存的值來自另一個串列(使用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)
輸出: [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])
uj5u.com熱心網友回復:
您可以通過一些串列理解來解決這個問題:
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}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368102.html
