Added "unique_iter_max" function
authorThierry Florac <tflorac@ulthar.net>
Mon, 29 Jun 2020 18:21:30 +0200
changeset 438 82836485546c
parent 437 b5131bd64de7
child 439 d2a70e493aa8
Added "unique_iter_max" function
src/pyams_utils/list.py
--- a/src/pyams_utils/list.py	Tue Jun 23 13:02:59 2020 +0200
+++ b/src/pyams_utils/list.py	Mon Jun 29 18:21:30 2020 +0200
@@ -115,6 +115,30 @@
                 yield element
 
 
+def unique_iter_max(iterable, key, sort_key):
+    """Get unique items sorted from an iterator
+
+    :param iterable: source iterable
+    :param key: function used to get unique key from items
+    :param sort_key: function used to get sort key from items
+
+    >>> from pyams_utils.list import unique_iter_max
+    >>> mylist = [('a', 1), ('b', 2), ('a', 3)]
+    >>> sorted(list(unique_iter_max(mylist,
+    ...                             key=lambda x: x[0],
+    ...                             sort_key=lambda x: x[1])))
+    [('a', 3), ('b', 2)]
+    """
+    seen = {}
+    for element in iterable:
+        k = key(element)
+        if k not in seen:
+            seen[k] = set()
+        seen[k].add(element)
+    for k, v in seen.items():
+        yield sorted(v, key=lambda x: sort_key(x))[-1]
+
+
 def random_iter(iterable, limit=1):
     """Get items randomly from an iterator