--- a/src/pyams_utils/list.py Mon Jul 02 17:41:09 2018 +0200
+++ b/src/pyams_utils/list.py Tue Jul 03 16:36:53 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)