Iterator To Return N Items At-a-time
Join the DZone community and get the full member experience.Join For Free
Copied from paul cannon's recipe here
def group(iterator, count): itr = iter(iterator) while True: yield tuple([itr.next() for i in range(count)])After the above definition, you can use it very easily.
>>> list(group([0, 1, 2, 3, 4, 5], 2)) [(0, 1), (2, 3), (4, 5)] >>> dataset = ['Nausori', 5, 'Namadi', 10, 'Suva', 3] >>> for place, value in group(dataset, 2): ... print '%s: %s' % (place, value) ... Nausori: 5 Namadi: 10 Suva: 3The above code is somewhat simplified. See the recipe for full discussion.