Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2D list slice

I looked around and could not find anything this specific, so here goes:

I have a list of lists:

S = [[3,4],[6,7],[10,12]]

and I would like to add the 0th index of the ith index element and on to the end of another list:

R = [5,6,7]

Normally with a 1D list I could say:

R = R + S[i:]

and take all of the elements from the ith index on, but I want the 0th index of the ith index of a 2D S. If we started at i = 1 I would end up with:

R = [5,6,7,6,10]

Also, I don't want to use for loops I want a list slice method that will work (if there is one) because it needs to be within a certain bound.

like image 695
Roklobster Avatar asked Nov 14 '15 22:11

Roklobster


2 Answers

You can use zip to transpose the matrix:

>>> S
[[3, 4], [6, 7], [10, 12]]
>>> zip(*S)
[(3, 6, 10), (4, 7, 12)]

Then slice the transposition:

>>> j=0
>>> i=1
>>> zip(*S)[j][i:]
(6, 10)

A tuple is iterable, so concatenation will work with a list:

>>> R = [5,6,7]
>>> R+=zip(*S)[j][i:]
>>> R
[5, 6, 7, 6, 10]
like image 64
dawg Avatar answered Nov 19 '22 08:11

dawg


As @jonrsharpe mentioned, numpy will do the trick for you:

import numpy as np
# Create two arrays
S = np.asarray([[3,4],[6,7],[10,12]])
R = np.asarray([5, 6, 7])
# Slice the S array
i = 1
sliced_S = S[i:, 0]
# Concatenate the arrays
R = np.concatenate((R, sliced_S))

Have a look at numpy's impressive documentation and indexing in particular.

like image 39
Till Hoffmann Avatar answered Nov 19 '22 10:11

Till Hoffmann