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.
#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


Messages In This Thread
RE: Zip on single element in nested sequence. - by nilamo - Jul-01-2017, 03:52 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: dictionary update sequence element #0 has length 1; 2 Jmekubo 4 36,215 Apr-28-2019, 07:25 PM
Last Post: Jmekubo
  Unable to locate element no such element gahhon 6 4,754 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,792 Jan-18-2019, 07:13 PM
Last Post: Larz60+
  Replace element in a nested list nagymusic 4 18,163 Nov-19-2018, 08:03 PM
Last Post: nilamo
  Change single element in 2D list changes every 1D element AceScottie 9 12,537 Nov-13-2017, 07:05 PM
Last Post: Larz60+
  Using nested for loop with a single list mikeavison 3 3,448 Aug-12-2017, 08:13 PM
Last Post: ichabod801
  Executing single unittest over a sequence volcano63 1 3,936 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