Python Forum
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


Zip on single element in nested sequence. - rhubarbpieguy - Jun-28-2017

How do I create the list c=[2,3,4] from the list a=[[1,2,3],[2,3,4],[3,4,5]]? In other words, how do I create a list from element [1] of a list containing nested sequences?

I know b,c,d=zip(*a) produces b=[1,2,3], c=[2,3,4], and d=[3,4,5].  That works well, but I don't need b and d.  It seems I should be able to use zip(*a[1]) or something of the sort but I have no success.

This is a minor problem but I must be missing something obvious.

my code here



RE: Zip on single element in nested sequence. - buran - Jun-28-2017

a = [[1,2,3],[4,5,6],[7,8,9]]
b = zip(*a)[1]
print b
c =  [x[1] for x in a]
print c
Output:
(2, 5, 8) [2, 5, 8]
by the way, no need for zip for the unpacking:
b, c, d = a
EDIT: Above applies when you want the i-th element of each element in a. In this case i=1

If you need the 1st element of a:
b = a[1]
Output:
[4, 5, 6]



RE: Zip on single element in nested sequence. - rhubarbpieguy - Jun-29-2017

The list comprehension works and is what I've used. However,zip(*a)[1] produces:

TypeError: 'zip' object is not subscriptable


RE: Zip on single element in nested sequence. - micseydel - Jun-29-2017

In Python 3, zip() doesn't return a list, it returns a specialized iterator. So you can't just ask for the nth item (1th item here). You'll have to operate on the iterator.


RE: Zip on single element in nested sequence. - nilamo - Jun-30-2017

In other words, list(zip(*a))[1].


RE: Zip on single element in nested sequence. - micseydel - Jun-30-2017

(Jun-30-2017, 07:00 PM)nilamo Wrote: In other words, list(zip(*a))[1].
That would be equivalent to Python 2, yes. Would be ok for small values of a. Unfortunately Python doesn't appear to have a very clean way of getting the nth value of an iterator so this is probably the cleanest thing to do.


RE: Zip on single element in nested sequence. - nilamo - Jun-30-2017

next() I guess?

So...
zipped = zip(*a) #maybe iter(zip(*a)), I didn't actually try
# ignore the first
next(zipped)
second_elem = next(zipped)



RE: Zip on single element in nested sequence. - micseydel - Jun-30-2017

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.


RE: Zip on single element in nested sequence. - ichabod801 - Jun-30-2017

compress?

compress(zip(*a), [0] * (n - 1) + [1])



RE: Zip on single element in nested sequence. - snippsat - Jul-01-2017

With Toolz a little nicer.
pip install toolz
>>> from toolz import nth
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> nth(1, zip(*a))
(2, 5, 8)