1 """Utilities for working with lists and sequences."""
5 Returns a single, flat list which contains all elements retrieved
6 from the sequence and all recursively contained sub-sequences
10 >>> [1, 2, [3, 4], (5, 6)]
11 [1, 2, [3, 4], (5, 6)]
13 From http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
17 if hasattr(el, '__iter__') and not isinstance(el, basestring):
18 result.extend(flatten(el))
23 def batch_size(items, size):
25 Retrieves items in batches of the given size.
29 [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
31 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
33 return [items[i:i+size] for i in xrange(0, len(items), size)]
35 def batches(items, number):
37 Retrieves items in the given number of batches.
41 [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
43 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
45 [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
47 [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
49 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
51 Initial batches will contain as many items as possible in cases where
52 there are not enough items to be distributed evenly.
55 [[1, 2], [3, 4], [5, 6], [7, 8], [9], [10]]
57 [[1, 2], [3, 4], [5, 6], [7], [8], [9], [10]]
59 [[1, 2], [3, 4], [5], [6], [7], [8], [9], [10]]
61 [[1, 2], [3], [4], [5], [6], [7], [8], [9], [10]]
63 [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
65 If there are more batches than items, empty batches will be appended
69 [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], []]
71 [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [], []]
73 div, mod= divmod(len(items), number)
77 return batch_size(items, div)
80 return [[item] for item in items] + [[]] * (number - mod)
81 elif div == 1 and not mod:
82 return [[item] for item in items]
84 # mod now tells you how many lists of 2 you can fit in
85 return ([items[i*2:(i*2)+2] for i in xrange(0, mod)] +
86 [[item] for item in items[mod*2:]])