views:

61

answers:

4

Simply put! there is this list say LST = [[12,1],[23,2],[16,3],[12,4],[14,5]] and i want to get all the minimum elements of this list according to its first element of the inside list. So for the above example the answer would be [12,1] and [12,4]. Is there any typical way in python of doing this? Thanking you in advance.

+1  A: 
m = min(LST, key=operator.itemgetter(0))[0]
print [x for x in LST if x[0] == m]
Ignacio Vazquez-Abrams
A: 
minval = min(x[0] for x in LST)
result = [x for x in LST if x[0]==minval]
interjay
+3  A: 

Two passes:

minval = min(LST)[0]
return [x for x in LST if x[0] == minval]

One pass:

def all_minima(iterable, key=None):
  if key is None: key = id
  hasminvalue = False
  minvalue = None
  minlist = []
  for entry in iterable:
     value = key(entry)
     if not hasminvalue or value < minvalue:
        minvalue = value
        hasminvalue = True
        minlist = [entry]
     elif value == minvalue:
        minlist.append(entry)
  return minlist

from operator import itemgetter
return all_minima(LST, key=itemgetter(0))
KennyTM
+1  A: 
Alex Martelli