[Tutor] comparison function/built-in needed

joe_schmoe geek_show at dsl.pipex.com
Wed Apr 6 21:26:09 CEST 2005


Kent Johnson wrote:
> joe_schmoe wrote:
> 
>> Greetings
>>
>> I am attempting to compare the items in two lists across two criteria 
>> - membership and position. For example:
>>
>> list_a = [ 0, 4, 3, 6, 8 ]
>> list_b = [ 1, 8, 4, 6, 2 ]
>>
>> Membership = There are 3 items that are common to both lists, that is 
>> 3 items in list_a have membership in list_b (viz: 4, 6, 8);
> 
> 
> Use sets:
>  >>> list_a = [ 0, 4, 3, 6, 8 ]
>  >>> list_b = [ 1, 8, 4, 6, 2 ]
>  >>> set(list_a).intersection(list_b)
> set([8, 4, 6])
> 
>> Position = There is 1 item in list_a that is also in the same position 
>> in both lists (viz: 6).
> 
> 
> Use zip() to iterate two lists in parallel and a list comprehension to 
> accumulate the results:
>  >>> [ a for a, b in zip(list_a, list_b) if a==b ]
> [6]
> 
> or if you want the position of the item use enumerate() to get the index:
>  >>> [ i for i, (a, b) in enumerate(zip(list_a, list_b)) if a==b ]
> [3]
> 
> Kent
> 
> 
Excellent Kent - that looks like that will work. I'll get back to you.

Cheers
/j


More information about the Tutor mailing list