[英]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])
I need to print after events the index of maximum values in d list Such that, (The longest event time is 100 for the event(s):4 7我需要在事件之后打印 d 列表中的最大值索引这样,(事件的最长事件时间为 100:4 7
you can simply create a function to find the max and index of max in a list and return the corresponding value of the same index in a second list.您可以简单地创建一个 function 来查找列表中的最大值和索引,并在第二个列表中返回相同索引的相应值。 here's the code:这是代码:
# 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)}")
Your current approach requires several passes on the list.您当前的方法需要在列表中多次通过。 This is not the most optimal.这不是最优化的。
Here is an algorithm to compute the maxima in only one pass.这是一种仅在一次通过中计算最大值的算法。 It is similar to the classical manual computation of a maximum except it handles all maxima and the fact that the maximum is computed one one list, but the saved value is from another list (using zip
)它类似于最大值的经典手动计算,除了它处理所有最大值以及最大值是在一个列表中计算的事实,但保存的值来自另一个列表(使用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]
Output: [4, 7]
Alternative without zip
:没有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])
You can solve this with a little list comprehension:你可以通过一些列表理解来解决这个问题:
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.