[Tutor] Comparing more than 2 lists

Michael Langford mlangford.cs03 at gtalumni.org
Thu Jan 24 09:36:05 CET 2008


You use a variation on bucket sort do to this:
http://en.wikipedia.org/wiki/Bucket_sort

You make a dict where the keys are the values in the lists, and a name
for each list is in the problem.

So you get something that looks like:

one: list1, list2
two: list1, list2, list3
etc

Doing this with collections.defaultdict is a breeze:
import collections

dd = collections.defaultdict(list)
for eachlist in lists:
   for each in eachlist:
       dd[each].append(getListName(eachlist))

Then to find the repeated elements you filter  where the list is of length > 1.

for each in dd:
     print "%s: %s" % (each, dd[each])

I'd provide code, but I'm not sure what an appropriate naming function
is for you, nor am I sure what you're doing with this when you're
done.

            --Michael



On Jan 24, 2008 3:15 AM, Fiyawerx <fiyawerx at gmail.com> wrote:
> I have been able to find a few articles on comparing 2 lists, but I have 4
> lists that I need to compare. I need to find any repeated elements and the
> list that they came from. For example,
>
> list1 = ['one', 'two', 'three']
> list2 = ['one', 'two', 'four', 'five']
> list3 = ['two', 'three', 'six', 'seven']
> list4 = ['three', 'five', 'six']
> https://mail.google.com/mail/#label/Pythontutor/117aadf8364dbf3b
Gmail - [Tutor] Comparing more than 2 lists - michael.langford at gmail.com
>
>  I need to be able to get along the lines of output:
> Element 'one' contained in list1 and list2
> Element 'two' contained in list1 and list2 and list3
> ...
> Element 'five' contained in list2 and list4
>
> etc.. and I can't quite figure out how to go about it
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com


More information about the Tutor mailing list