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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Jamie
  • 13
  • 1
  • 4

2 Answers2

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]
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • One can suggest `itemgetter` instead of `lambda` https://stackoverflow.com/questions/17243620/operator-itemgetter-or-lambda, Though no difference in small-medium lists. – Rockybilly Oct 26 '17 at 01:30
  • Is there another way to iterate this without using key=lambda ? – Jamie Oct 26 '17 at 01:34
  • @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 – TerryA Oct 26 '17 at 01:34
  • If multiple lists have the same value as an element. How would `lambda` or `itemgetter` get them? – user977828 Nov 12 '20 at 20:39
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.

nomoreabond2017
  • 150
  • 2
  • 5