2010-10-25 37 views
1

我是一個Python新手,我與列表工作了2個月,我有一些問題。我有一些列表,他們有重複的項目。我可以得到2個列表之間的重複項目,現在我想要列表的數量和深度增加像這樣的例子: http://i219.photobucket.com/albums/cc213/DoSvn/example.png。 我想從紅色部分獲得重複項目的父母,而不是藍色部分或這些重複項目的列表。我該怎麼做 ? 謝謝:)如何從列表中獲取重複項目的最小列表?


更新: 感謝您的答案:d我用套裝,它的偉大。但是,我想如果我不知道列表的大小,只是不知道列表的大小,他們是動態列表,我可以得到像這樣的例子的所有紅色部分:http://i219.photobucket.com/albums/cc213/DoSvn/example02.png

+0

你有沒有考慮過用套代替名單? – 2010-10-25 04:52:23

+0

巧合地描述了你所描述的與維恩圖相似之處(http://en.wikipedia.org/wiki/Venn_diagram) – 2010-10-25 05:06:20

+0

感謝你的回答:D我已經使用Set,它很棒。但是我想如果我不知道列表的大小和其他什麼,他們是動態列表,我可以得到像這樣的例子的所有紅色部分:http://i219.photobucket.com/albums/ cc213/DoSvn/example02.png? – 2010-10-25 05:59:30

回答

1

如果您正在尋找這樣的事情:http://i219.photobucket.com/albums/cc213/DoSvn/example02.png

然後你可以嘗試Counter(可用於Python 2.7+)。它應該是這樣的:

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 

或者與舊蟒蛇:

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 
+0

我使用python 2.5因爲GAE :)我想我會使用「設置」一些條件來解決問題,不成功,但也許它會給我一個好的結果在我的應用程序中使用:D謝謝:) – 2010-10-25 07:01:38

+1

在這裏,爲Python 2.5的一個版本 – eumiro 2010-10-25 07:04:25

0

使用集合,你可以得到交集,減法或任何複雜的組合

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 

輸出:

set([5]) 
+0

謝謝:)你的回答很有用:D我有另外一個問題,你能幫助我嗎?我想如果我不知道列表的大小,只是列表的大小,他們是動態列表,我可以得到像這樣的例子的所有紅色部分:http://i219.photobucket.com/albums/cc213 /DoSvn/example02.png? – 2010-10-25 06:00:39

+0

@ ducanh.do88 - 更新您的問題與您的後續問題 – eumiro 2010-10-25 06:32:35