vector subscripts in Python?
Alexander Schmolck
a.schmolck at gmx.net
Thu Jun 12 12:02:15 EDT 2003
beliavsky at aol.com writes:
> 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
As already pointed out, a list comprehension will do what you want, but since
I find this behavior useful quite often I think wrapping it up in a function
is worthwhile (note that it allows works for dicts and other iterables).
def at(iterable, indices):
return [iterable[i] for i in indices]
In [5]: at(xx, ii)
Out[5]: [1, 9]
In [6]: at({'a':1, 'b':2}, ['a','b'])
Out[6]: [1, 2]
'as
More information about the Python-list
mailing list