Property testing in lists
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Tue Sep 12 19:15:34 EDT 2000
Dan Brown wrote in comp.lang.python:
> I'm a python newbie (my work is mostly in scientific computing, so I use
>
> Matlab for most of my coding needs).
>
> I'd like to be able to identify the indexes of all members of a list
> that
> have a particular property. Certainly, there's lots of ways to do it;
> here's two examples with testing for being one more than a multiple of
> 4.
>
> >>> N = [1, 10, 194, 148, -403]
> >>> map (lambda x: x[1],filter (lambda x: x[0] % 4 == 1, map (None, N,
> range(len(N)))))
> [0, 4]
> >>> index = []
> >>> for i in range (len(N)):
> ... if (N[i] % 4 == 1):
> ... index.append(i)
> ...
> >>> index
> [0, 4]
>
> However, these are both much more disgusting than the equivalent Matlab
> code: [Lists in Matlab are indexed starting at 1.]
>
> >> N = [1 10 194 148 -403];
> >> find (mod (N,4) == 1)
>
> ans =
>
> 1 5
>
> Is there an equivalent form in Python which is pretty like the Matlab
> code,
> or am I just barking up the wrong tree?
How about this one:
N = [1, 10, 194, 148, -403]
filter(lambda x,N=N: N[x] % 4 == 1, range(len(N)))
It's more verbose than Matlab, but well, just make it into a function once,
and you'll never need to type it again...
Python has nice ways to make a list of the *values* that have the property,
like filter() and list comprehensions in 2.0(beta), but not for the indices
I think. So just view it as a property of the index :-)
--
Remco Gerlich, scarblac at pino.selwerd.nl
"This gubblick contains many nonsklarkish English flutzpahs, but the
overall pluggandisp can be glorked from context" (David Moser)
More information about the Python-list
mailing list