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 ?
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
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])
精彩评论