Home > Software engineering >  How can I get the index of max values in list and then print the values from another list with max&#
How can I get the index of max values in list and then print the values from another list with max&#

Time:11-28

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

CodePudding user response:

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)}")

CodePudding user response:

max returns the highest value, not its index. See here for an explanation of how to find the index (Finding the index of an item in a list) to find the index.

Then you simply do:

maxVal = max(g)
maxInd = g.index(maxVal)
ll = d[maxInd]

print("The longest event time is",maxVal,"for the event(s):",ll)
  • Related