indexing lists/arrays question
Tim Chase
python.list at tim.thechases.com
Thu May 13 20:18:16 EDT 2010
On 05/13/2010 12:51 PM, a wrote:
>> If your two arrays are of the same length, you can do things like
>>
>> a = [2,3,3,4,5,6]
>> b = ['a', 'b', 'c', 'd', 'e', 'f']
>>
>> print [m for (n,m) in zip(a,b) if n == 3]
>>
>> and skip the indexes altogether.
>
> mmm, that's clever, thanks. although i don't know why it works yet.
> at least i found a good user group!
the zip() function takes its parameters and returns a list
containing paired items from each list:
>>> print zip(a,b) # using the above-defined a/b
[(2, 'a'), (3, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]
The list comprehension then iterates over the elements of that
list, assigned as (n,m), testing "n" (the numeric value you want
to test) and returning "m" (the corresponding value in "b")
-tkc
More information about the Python-list
mailing list