[Tutor] how to compare elements of 2 lists

Chris Fuller cfuller084 at thinkingplanet.net
Tue Dec 25 21:36:59 CET 2007


The most concise way to do this is to transpose the list (convert a axb array
to bxa), then complare the elements that are pairs of one value each of the 
original lists.

You have two lists, a and b.  Put these into a list and you have a 2x6 
2d "array".

>>> [a,b]
[[4, 3, 2, 6, 7, 9], [8, 6, 3, 3, 2, 7]]

A quick way to do a transposition is to use the built-in zip() function. This 
doesn't do error checking! If you need to do this in production code, you 
need to check that the lists are of even lengths. zip() will truncate the 
lists until they are all teh same size!

>>> zip(*[a,b])
[(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]

So, to get a list of booleans, you can do this:
>>> [x>y for x,y in zip(*[a,b])]
[False, False, False, True, True, True]

Cheers

On Tuesday 25 December 2007 09:00, sith . wrote:
> Hi,
> I've read the posts on comparing 2 lists and couldn't find the answer to my
> question. I have 2 lists
>   a = [4,3,2,6,7,9]
> b = [8,6,3,3,2,7]
>   How can I determine if the elements in a are larger or smaller than the
> elements in b.
>
>   for i in a:
>     for u in b:
>         i > u
>   does not return the result I seek.
>
> In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> compared to all the elements in b. I'd like
> 4 to 8,
> 3 to 6,
> 2 to 3 and so on; like 2 columns in excel, the third column would be a new
> list of boolean values. Can someone help please?  Thank you.
>
>
> ---------------------------------
> Never miss a thing.   Make Yahoo your homepage.


More information about the Tutor mailing list