2013-04-25 48 views
3

我是python的新手,我遇到了障礙。我有一個python列表,每行包含一個列表。基本上,我想將列表中共享值的列表結合起來。例如,下面的 就是我的python列表目前看到的內容,以及在附加命令執行後我希望數據看起來像什麼。如何將python列表和共享項目合併到新列表中

我知道這類問題對於集合和交叉點是理想的,但我只是無法讓它們正常工作。我也看到了一篇使用索引的文章,但這也不適合我。

列表的樣子:

[ 
    ['mary', 'home'], 
    ['mary', 'school'], 
    ['mary', 'work'], 
    ['bob', 'home'], 
    ['bob', 'school'], 
    ['bob', 'work'], 
    ['tom', 'work'], 
    ['tom', 'school'], 
    ['tom', 'home'], 
    ['bill', 'vacation'], 
] 

我希望它是什麼樣子:

[ 
    ['mary', 'bob', 'tom', 'home', 'school', 'work'], 
    ['bill', 'vacation'], 
] 

回答

-1
#original list 
lists = [ 
     ['mary', 'home'], 
     ['mary', 'school'], 
     ['mary', 'work'], 
     ['bob', 'home'], 
     ['bob', 'school'], 
     ['bob', 'work'], 
     ['tom', 'work'], 
     ['tom', 'school'], 
     ['tom', 'home'], 
     ['bill', 'vacation']] 

#remove sublists from lists 
listTemp = [] 
for list in lists: 
    for item in list: 
     listTemp.append(item) 

#get items from list that have duplicates 
listMultiple = [] 
seen = set() 
seen_add = seen.add 
setTemp = set(x for x in listTemp if x in seen or seen_add(x)) 
for item in setTemp: 
    listMultiple.append(item) 

#get items from list that do not have duplicates 
listSingle = [x for x in listTemp if listTemp.count(x) == 1] 

print listMultiple 
# >>> listMultiple 
# ['school', 'work', 'tom', 'home', 'bob', 'mary'] 

print listSingle 
# >>> listSingle 
# ['bill', 'vacation'] 
# lists = [listMultiple, listSingle] 
+0

謝謝拉爾斯,它工作得很好!我特別喜歡你如何分割單打和倍數。 – owen 2013-04-26 16:38:50

+0

雖然這個答案恰好適用於給定的具體示例數據,但在一般情況下它會失敗。例如,用[['a','b'],['a','c'],['d','e'],['d','f'],['g' ,'h']]'它給出'listMultiple == ['a','d']'和'listSingle == ['b','c','e','f','g',' h']' - 換句話說,它只是計算元素的出現次數,而不是將列表與共享元素結合起來。 – 2013-04-26 17:30:13

3

你的榜樣的數據表明,爲了在你輸入的數據很重要,這將情況複雜化。假設它實際上只是一個例子,爲了重要的是,套確實是解決問題的理想方式:

data = [ 
    ['mary', 'home'], 
    ['mary', 'school'], 
    ['mary', 'work'], 
    ['bob', 'home'], 
    ['bob', 'school'], 
    ['bob', 'work'], 
    ['tom', 'work'], 
    ['tom', 'school'], 
    ['tom', 'home'], 
    ['bill', 'vacation'], 
] 

combined = [] 

for subset in [set(d) for d in data]: 
    for candidate in combined: 
     if not candidate.isdisjoint(subset): 
      candidate.update(subset) 
      break 
    else: 
     combined.append(subset) 

這將使用Python的for-else結構,這不是每個人都熟悉。 combined將包含一組列表,因此您可能需要根據您的用例將它們轉換爲列表。

+0

Thanks Zero,它工作得很好!你說得對,訂單並不重要。 – owen 2013-04-26 16:38:02

相關問題