indexing lists/arrays question
Matthew Wilson
matt at tplus1.com
Thu May 13 11:01:08 EDT 2010
On Thu 13 May 2010 10:36:58 AM EDT, a wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)
>
> then i want to reference these in a
>
> ie what i would do in IDL is
>
> b=where(a eq 3)
> a1=a(b)
There's several solutions. Here's one:
It is a recipe for madness to use a list of integers and then talk
about the position of those integers, so I renamed your list to use
strings.
>>> a = ['two', 'three', 'three', 'four','five', 'six']
Now I'll use the enumerate function to iterate through each element and
get its position::
>>> for position, element in enumerate(a):
... print position, element
...
0 two
1 three
2 three
3 four
4 five
5 six
And now filter:
>>> for position, element in enumerate(a):
... if element == 'three':
... print position, element
1 three
2 three
And now do something different besides printing:
>>> b = []
>>> for position, element in enumerate(a):
... if element == 'three':
... b.append(position)
And now we can rewrite the whole thing from scratch to use a list
comprehension:
>>> [position for (position, element) in enumerate(a) if element == 'three']
[1, 2]
HTH
Matt
More information about the Python-list
mailing list