vector subscripts in Python?
Gary Herron
gherron at islandtraining.com
Wed Jun 11 19:35:14 EDT 2003
On Wednesday 11 June 2003 04:12 pm, beliavsky at aol.com wrote:
> Does Python have the equivalent of "vector subscripts" of Fortran 95?
> The code below illustrates what I am looking for -- with better syntax.
>
> def subscript(xx,ii):
> # return the elements in xx subscripted by ii
> y = []
> for i in ii: y.append(xx[i])
> return y
>
> ii = [0,2]
> xx = [1,4,9]
> print subscript(xx,ii) # returns [1, 9]; in F95, "print*,xx(ii)" is
> analogous
List comprehension (as it's called) lets you do things like this,
although it's much more general and powerful than your request.
>>> ii = [0,2]
>>> xx = [1,4,9]
>>> print [xx[i] for i in ii]
[1, 9]
>>>
See the following manual section:
http://www.python.org/doc/current/tut/node7.html#SECTION007140000000000000000
Gary Herron
More information about the Python-list
mailing list