Question

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.

Was it helpful?

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'

OTHER TIPS

Combine filtering with min():

from operator import itemgetter

id = min(filter(itemgetter(1), mylist), key=itemgetter(1))[0]
  • The filter(itemgetter(1), mylist) removes all elements whose second element is falsey; False in a boolean context. That includes 0 and None.

  • min(..., key=itemgetter(1)) finds the lowest value based on the key you give it; so the list with the lowest float value after filtering.

  • [0] selects the id entry from your list.

A quick demo (with a syntactically correct input list):

>>> mylist = [
...     ['someid-1', None], 
...     ['someid-2', 4545.474], 
...     ['someid-3', 200.1515], 
...     ['someid-4', None], 
...     ['someid-5', 0]
... ]
>>> from operator import itemgetter
>>> min(filter(itemgetter(1), mylist), key=itemgetter(1))[0]
'someid3'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top