Python Forum
Zip on single element in nested sequence.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Zip on single element in nested sequence.
#11
(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))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#12
(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)
Reply
#13
A regular loop and islice both work but the comprehension will use memory proportional to the index you want, rather than a fixed amount.
Reply
#14
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.
Reply
#15
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: dictionary update sequence element #0 has length 1; 2 Jmekubo 4 35,609 Apr-28-2019, 07:25 PM
Last Post: Jmekubo
  Unable to locate element no such element gahhon 6 4,520 Feb-18-2019, 02:09 PM
Last Post: gahhon
  Using xpath to get value of a nested element name using tag named xq1xq1xq1 3 9,541 Jan-18-2019, 07:13 PM
Last Post: Larz60+
  Replace element in a nested list nagymusic 4 17,904 Nov-19-2018, 08:03 PM
Last Post: nilamo
  Change single element in 2D list changes every 1D element AceScottie 9 12,100 Nov-13-2017, 07:05 PM
Last Post: Larz60+
  Using nested for loop with a single list mikeavison 3 3,320 Aug-12-2017, 08:13 PM
Last Post: ichabod801
  Executing single unittest over a sequence volcano63 1 3,859 May-11-2017, 11:11 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020