![]() |
Zip on single element in nested sequence. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Zip on single element in nested sequence. (/thread-3825.html) Pages:
1
2
|
RE: Zip on single element in nested sequence. - ichabod801 - Jul-01-2017 (Jul-01-2017, 03:52 AM)snippsat Wrote: With Toolz a little nicer. It appears they are just using islice: next(itertools.islice(seq, n, None)) RE: Zip on single element in nested sequence. - nilamo - Jul-01-2017 (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) RE: Zip on single element in nested sequence. - micseydel - Jul-01-2017 A regular loop and islice both work but the comprehension will use memory proportional to the index you want, rather than a fixed amount. RE: Zip on single element in nested sequence. - nilamo - Jul-01-2017 Either way, I think a loop is about the best you can get and still be generic enough to work with things like generators that emit streams of data from sockets, since you can't exactly skip ahead for that. RE: Zip on single element in nested sequence. - micseydel - Jul-01-2017 I would prefer islice over a loop. It might be smart enough at some point to be able to negotiate "skipping ahead" in a generator in the future but I feel like a loop will never be. |