Posts: 13
Threads: 7
Joined: Jan 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.
Posts: 8,167
Threads: 160
Joined: Sep 2016
Jun-28-2017, 01:06 PM
(This post was last modified: Jun-28-2017, 01:06 PM by buran.)
1 2 3 4 5 |
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:
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:
Output: [4, 5, 6]
Posts: 13
Threads: 7
Joined: Jan 2017
The list comprehension works and is what I've used. However,zip(*a)[1] produces:
TypeError: 'zip' object is not subscriptable
Posts: 2,342
Threads: 62
Joined: Sep 2016
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.
Posts: 3,458
Threads: 101
Joined: Sep 2016
In other words, list(zip(*a))[1] .
Posts: 2,342
Threads: 62
Joined: Sep 2016
(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.
Posts: 3,458
Threads: 101
Joined: Sep 2016
Jun-30-2017, 08:30 PM
(This post was last modified: Jun-30-2017, 08:30 PM by nilamo.)
next() I guess?
So...
1 2 3 4 |
zipped = zip ( * a)
next (zipped)
second_elem = next (zipped)
|
Posts: 2,342
Threads: 62
Joined: Sep 2016
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.
Posts: 4,220
Threads: 97
Joined: Sep 2016
compress?
1 |
compress( zip ( * a), [ 0 ] * (n - 1 ) + [ 1 ])
|
Posts: 7,324
Threads: 123
Joined: Sep 2016
With Toolz a little nicer.
pip install toolz
1 2 3 4 |
>>> from toolz import nth
>>> a = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]]
>>> nth( 1 , zip ( * a))
( 2 , 5 , 8 )
|
|