Jul-01-2017, 03:52 PM
(Jun-30-2017, 10:36 PM)micseydel Wrote: Yeah, that would work for n=2, but it doesn't seem super elegant to me. I wish there was something in itertools to get the nth item of an iterator.
Seems easy enough to make, though:
>>> def nth(ndx, collection): ... last = None ... for _ in range(0, ndx+1): ... last = next(collection) ... return last ... >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> nth(1, zip(*a)) (2, 5, 8)Or if you prefer comprehensions:
>>> def nth(ndx, collection): ... vals = [next(collection) for _ in range(0, ndx+1)] ... return vals[-1] ... >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> nth(1, zip(*a)) (2, 5, 8)