Added random iterator
authorThierry Florac <thierry.florac@onf.fr>
Tue, 03 Jul 2018 14:19:55 +0200
changeset 213 7d552669f29f
parent 212 c110fd0251ff
child 214 e01d3a0db652
child 275 59452a6f51a8
Added random iterator
src/pyams_utils/list.py
--- a/src/pyams_utils/list.py	Mon Jul 02 08:57:56 2018 +0200
+++ b/src/pyams_utils/list.py	Tue Jul 03 14:19:55 2018 +0200
@@ -15,6 +15,7 @@
 
 # import standard library
 from itertools import filterfalse
+from random import random, shuffle
 
 # import interfaces
 
@@ -102,3 +103,23 @@
             if k not in seen:
                 seen_add(k)
                 yield element
+
+
+def random_iter(iterable, limit=1):
+    """Get items randomly from an iterator
+
+    >>> from pyams_utils.list import random_iter
+    >>> mylist = [1, 2, 3, 2, 1]
+    >>> list(random_iter(mylist, 2))
+    [..., ...]
+    """
+    selected = [None] * limit
+    for index, item in enumerate(iterable):
+        if index < limit:
+            selected[index] = item
+        else:
+            selected_index = int(random() * (index+1))
+            if selected_index < limit:
+                selected[selected_index] = item
+    shuffle(selected)
+    return iter(selected)