Finding a list in a list of lists with the max value by given index and returning its first value

后端 未结 2 1417
甜味超标
甜味超标 2021-01-16 14:44

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

2条回答
  •  囚心锁ツ
    2021-01-16 15:32

    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.

提交回复
热议问题