How to get all the minimal elements according to their first element in the internal list in a nested list?

Simply put! this list says LST = [[12,1],[23,2],[16,3],[12,4],[14,5]], and I want to get all the minimal elements of this list according to its first element in the internal list. So, for the above example, the answer will be [12,1]and [12,4]. Is there a typical way in python to do this? Thank you in advance.

+3
source share
4 answers

A compact one-pass solution requires sorting the list — technically O(N log N)for a Nlong list, but Python sorting is so good, and so many sequences “just happen” to have a built-in order in them (which they timsortskillfully use to go faster) that sort-based solutions sometimes have amazingly good performance in the real world.

Solution 2.6 or better is required here:

import itertools
import operator
f = operator.itemgetter(0)

def minima(lol):
  return list(next(itertools.groupby(sorted(lol, key=f), key=f))[1])

To understand this approach, an inside-out search helps.

f, i.e. operator.itemgetter(0), is a key function that selects the first element of its argument for sequencing purposes. The goal itself operator.itemgetteris to create such functions easily and compactly.

sorted(lol, key=f), , - lol, . key=f, , , " " - .. - key=f . , ( , ), , .

itertools.groupby(sorted(lol, key=f), key=f) "", : ( sorted ) key. , , , f , , ( ), . groupby , , lol ( groupby , ).

yield ed by groupby k, g: k, f(i) , g, .

next ( , Python 2.6), , - , , , ( , , , groupby). Python groupby(...).next() ( next , ), 2.6.

, , next(...) k, g, k - ( ) , g - .

, [1] , , .

, ( ), list(...) .

, ? , - minima , @Kenny ( , "" ). , , , ( , , , c, & c; -).

+3

:

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

:

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))
+5
m = min(LST, key=operator.itemgetter(0))[0]
print [x for x in LST if x[0] == m]
+2
source
minval = min(x[0] for x in LST)
result = [x for x in LST if x[0]==minval]
-1
source

Source: https://habr.com/ru/post/1760882/


All Articles