简体   繁体   中英

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

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. 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 )

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM