Kevin
Kevin

Reputation: 2050

Create list out of a particular element of sublists

My title is probably incredibly confusing, so I'll just give an example. For the following list:

 x = [ [1,2,3], [4,5,6], [7,8,9] ]

So, if you wanted from an index of one, the resultant list would be:

 [2,5,8]

Is there a short way to do this? Obviously you can iterate through the outside list and simply grab each element of index 1, but is there any easy way to do this in one line with, for example, slce notation?

I'm aware that it's possible to do this in one line with something like:

 list(map(lambda f : f[1], x))

But that's exactly what I described above (just using an implicit loop).

If it helps, it is safe to assume that all the elements will be indexable.

Upvotes: 0

Views: 133

Answers (3)

Nafiul Islam
Nafiul Islam

Reputation: 82550

No matter what you do, there will always be implicit looping somewhere.

You can also use zip (look ma! no loops (no for keyword)):

>>> zip(*x)[0]
(1, 4, 7)
>>> zip(*x)[1]
(2, 5, 8)
>>> zip(*x)[2]
(3, 6, 9)

Or list comprehensions:

>>> x = [ [1,2,3], [4,5,6], [7,8,9] ]
>>> l = [var[1] for var in x]
>>> l
[2, 5, 8]

If you wanted some other index:

>>> [var[0] for var in x]
[1, 4, 7]
>>> [var[2] for var in x]
[3, 6, 9]

Upvotes: 3

unutbu
unutbu

Reputation: 880389

In [3]: x = [ [1,2,3], [4,5,6], [7,8,9] ]

In [4]: import operator

In [5]: map(operator.itemgetter(1), x)
Out[5]: [2, 5, 8]

Upvotes: 2

Prashant Kumar
Prashant Kumar

Reputation: 22609

To directly index your array like that, you may wish to use a numpy.array. Then you can use slice notation.

Upvotes: 0

Related Questions