pythonlistminnonetypetype-2-dimension

Python index min value list of list


I have a 2D list of lists in Python and I need to find the lowest float in column 1, and then return the value in the same row, but at column 0.

mylist =  [['someid-1', None] ,['someid-2', 4545.474] ,['someid-3', 200.1515] ,['someid-4', None] ,['someid-4', 0]]

In this case I want returned: someid-3

At the moment I am appending only values which are not None and then do this: (which seems complicated for such a "simple" task)

    mylist.sort(key=lambda x: x[1])
    if len(temp_op_distance_list) != 0 and temp_op_distance_list[0][1] != None:
        return temp_op_distance_list[0][0]

Some info on the overall Python project.

The list is about 8000 entries with values 'None' and some floats. This code collects distance to a Mousepointer in 3D space and test all 3D objects in the Programm. When there is the value None the object was not hit.

Edited: Proper list formatting - Of course you all are right, pointing out that my list is not correct. Sorry about that.


Solution

  • Assuming your list is a proper Python List

    mylist =  [['someid-1', None] ,['someid-2', 4545.474] ,['someid-3', 200.1515] ,['someid-4', None] ,['someid-4', 0]]
    

    You can simply create a generator expression, selecting only the Valid Non Zero Items and determine the min using the key as itemgetter(1)

    >>> from operator import itemgetter
    >>> min((e for e in mylist if e[1]), key = itemgetter(1))[0]
    'someid-3'