2013-10-25 95 views
0

如果我創建一個包含列表這樣的兩個列表中:列表理解列表

bad_list.append(['blue_widget', 'cracked', '776']) 
bad_list.append(['red_widget', 'not_smooth', '545']) 
bad_list.append(['yellow_widget', 'spots', '35']) 
bad_list.append(['green_widget', 'smells_bad', '10']) 
bad_list.append(['purple_widget', 'not_really_purple', '10']) 


good_list.append(['blue_widget', 'ok', '776']) 
good_list.append(['red_widget', 'ok', '545']) 
good_list.append(['green_widget', 'ok', '10']) 

我很想能夠在惡劣的使用列表中理解到兩個列表比較,並刪除 所有項目使用第一個元素 (x_widget)作爲要比較的項目,將列表顯示在良好列表中。使用上面的例子,我應該留下:

['yellow_widget', 'spots', '35'] 
['purple_widget', 'not_really_purple', '10'] 

我一直在使用列表理解試着和它的作品,但在新的列表不保留的每一行:當我使用內容打印出來

final_list = [x for x in bad_list[0] if x not in good_list[0]] 

對於final_list中的項目我得到類似於:

yellow_widget 
smells_bad 
10 

任何線索將不勝感激。

+0

'bad_list [0 ]'和'good_list [0]'是列表的第一項,而不是冷杉t列。 - 我現在無法想象這樣做。可能你必須使用常規的'for'循環。 –

回答

0

沒有真正以任何方式優化,但這應該工作:http://codecube.io/AD7RHA

bad_list=[] 
good_list=[] 

bad_list.append(['blue_widget', 'cracked', '776']) 
bad_list.append(['red_widget', 'not_smooth', '545']) 
bad_list.append(['yellow_widget', 'spots', '35']) 
bad_list.append(['green_widget', 'smells_bad', '10']) 
bad_list.append(['purple_widget', 'not_really_purple', '10']) 


good_list.append(['blue_widget', 'ok', '776']) 
good_list.append(['red_widget', 'ok', '545']) 
good_list.append(['green_widget', 'ok', '10']) 

# ['yellow_widget', 'spots', '35'] 
# ['purple_widget', 'not_really_purple', '10'] 

labels = zip(*good_list)[0] 

new_bad_list=[] 

for item in bad_list: 
    if item[0] not in labels: 
     new_bad_list.append(item) 

print new_bad_list 

或這一個班輪:

new_bad_list=[item for item in bad_list if item[0] not in zip(*good_list)[0]] 
0

試試這個:

print [ele for ele in bad_list if ele[0] not in [i[0] for i in good_list]] 

輸出:

[['yellow_widget', 'spots', '35'], ['purple_widget', 'not_really_purple', '10']] 
0

有一個更有效的解決方案。從你的列表中進行設定

bad_set = set(bad_list) 
good_set = set(good_list) 

現在去除壞列表中存在的良好列表中的所有項目,可以簡單。減去套:

bad_set - good_set 

轉換重新設置列表中,如果你喜歡。

+0

這是行不通的,因爲OP有一個列表清單,並且清單不可排列。我確定你的意思是'bad_set = set(x [0] for bad_list')等等,但你需要更多的工作,而不僅僅是設置差異。 – SethMMorton

0

最簡單的方法是:

final_list = [x for x in bad_list if x[0] not in [x[0] for x in good_list]] 

但是請注意,以測試元素的現有列表中是不是有效率的。

所以,你可以先建立一個集:

good_list_names = set([x[0] for x in good_list]) 

然後:

final_list = [x for x in bad_list if x[0] not in good_list_names] 
1

一個襯墊

[x for x in bad_list if any(x[0] == y[0] for y in good_list)] 

*感謝@Bakuriu

+3

請注意,您可以避免列出「任何」的理解。只需使用genexp:'any(x [0] == y [0] for y in good_list)''。這樣你可以避免創建一個列表。還有'任何'短路,所以它在平均情況下會更快。如果函數需要的不止一個參數,則必須將genexp括在'('和')'中,如:'filter(some_function,(x for the_genexp中的x))'。 – Bakuriu