views:

91

answers:

2

Hi everyone, I'm a Python newbie, I worked with list for 2 months and I have some questions. I have some list and they have duplicate items. I can get duplicate items between 2 lists, now I want the number of lists and the deepness increased like this example: http://i219.photobucket.com/albums/cc213/DoSvn/example.png. I want to get parents of duplicate items from red part, not blue part or list of these duplicate items. How can I do it ? Thank you :)


Update: Thank for your answers :D I have used Set and it's great. But I guess if I don't know about the size of the list of lists and nothing more, they are dynamic lists, can I get all of the red parts like that example: http://i219.photobucket.com/albums/cc213/DoSvn/example02.png ?

A: 

Use sets and you can get intersection, union, subtraction or any complex combination

s1 = set([1, 2, 3, 4, 5])
s2 = set([4, 5, 6, 7, 8])
s3 = set([1, 3, 5, 7, 9])

# now to get duplicate between s1, s2 and s2 take intersection
print s1&s2&s3

output:

set([5])
Anurag Uniyal
Thank you :) your answer is useful :D I have another question, can you help me ? I guess if I don't know about the size of the list of lists and nothing more, they are dynamic lists, can I get all of the red parts like that example: http://i219.photobucket.com/albums/cc213/DoSvn/example02.png ?
ducanh.do88
@ducanh.do88 - update your question with your subsequent problem
eumiro
A: 

If you are searching something like this: http://i219.photobucket.com/albums/cc213/DoSvn/example02.png

Then you can try the Counter (available in Python 2.7+). It should work like this:

from collections import Counter

c = Counter()
for s in (listOfLists):
    c.update(s)

for item, nbItems in c.iteritems():
    if nbItems == 3:
        print '%s belongs to three lists.' % item

Or with older Pythons:

counter = {}

for s in (listOfLists):
    for elem in s:
        counter[elem] = counter.get(elem, 0) + 1

for item, nbItems in counter.iteritems():
    if nbItems == 3:
        print '%s belongs to three lists.' % item
eumiro
I'm using python 2.5 because of GAE :) I think I will use "Set" with some conditions to solve the problem, not successfully but maybe it will give me a good result to use in my application :D thank you :)
ducanh.do88
Here you are, a version for Python 2.5
eumiro