2013-10-25 96 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