1

I have a list of lists and I want to find the max value by one index in the lists, in this case [5].

Once I have the max value, how would I find where that occurs and return the first element of that list?

For example:

inputlist = [[70, 'Cherry St,', 43.684371, -79.316756, 23, 9, 14, True, True],
             [78, 'Cow Rd', 43.683378, -79.322961, 15, 13, 2, True, False]]

How can I get my function to return 78 as it contains the maximum value of index[5] in my list of lists?

0

2 Answers 2

2

Use the max() function, but pass through an argument to check a specific index:

max(inputList, key=lambda x: x[5])

This returns the sublist in inputList that has the greatest value at index 5. If you want to actually access this value, add [5] to the end of the statement.

Since it seems that you want the ID of the list with the maximum 5th element, add [0] to the end:

max(inputList, key=lambda x: x[5])[0]
Sign up to request clarification or add additional context in comments.

4 Comments

One can suggest itemgetter instead of lambda stackoverflow.com/questions/17243620/…, Though no difference in small-medium lists.
Is there another way to iterate this without using key=lambda ?
@Jamie You could manually use a for-loop and find the maximum without using the max() function, but that kinda goes against the whole idea of Python
If multiple lists have the same value as an element. How would lambda or itemgetter get them?
0

This is what you can do, using list comprehension twice

inputlist = [[70, 'Cherry St,', 43.684371, -79.316756, 23, 9, 14, True, True],
[78, 'Cow Rd', 43.683378, -79.322961, 15, 13, 2, True, False]]

The max value at the 5th index , considering all the list in inputlist. You can use this for any(n) no of member list.

value_5th = max([listt[5] for listt in inputlist])

Once you reach at that:

This will give you the first element of that member list which has that largest/max element at the 5th index amongst all other member list.Plz note that this will work even if multiple member lists have same max element at their 5th index

Your_ans = [ listt[0] for listt in inputlist if value_5th in listt]

Just trying to give you a more robust solution.Although ans given above is quite clever in my view.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.