Python 列表中列表的列表理解
如果我创建两个包含如下列表的列表:Python 列表中列表的列表理解,python,Python,如果我创建两个包含如下列表的列表: 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(['purp
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_小部件)作为要比较的项目。使用上述示例,我应该留下:
['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_列表中的项目打印出内容时,我得到如下结果:
yellow_widget
smells_bad
10
任何线索都将不胜感激。并非通过任何方式真正优化,但这应该是可行的: 或者这一行:
new_bad_list=[item for item in bad_list if item[0] not in zip(*good_list)[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']]
有一个更有效的解决方案。从你的清单上做一套
bad_set = set(bad_list)
good_set = set(good_list)
现在,要删除好列表中存在的坏列表中的所有项目,您可以简单地减去集合:
bad_set - good_set
如果愿意,可以将设置转换回列表。最简单的方法是:
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]
一班轮
[x for x in bad_list if any(x[0] == y[0] for y in good_list)]
*谢谢@Bakuriu
坏列表[0]
和好列表[0]
是列表的第一个条目,而不是第一列。-我现在想不出一个班轮公司能做到这一点。可能您必须对循环使用常规的。请注意,您可以避免对任何
的列表理解。只需使用genexp:any(x[0]==y[0]表示良好列表中的y)
。这样可以避免创建列表。同时任何
短路,因此在一般情况下会更快。如果函数需要的参数不止一个,则必须将genexp括在(
和)
中,例如:过滤器(某些函数,(x代表x在\u genexp中))
。这不起作用,因为OP有一个列表列表,并且列表不可散列。我肯定你的意思是bad_set=set(bad_list中x的x[0])
等等,但是你需要做的工作不仅仅是取集差。
[x for x in bad_list if any(x[0] == y[0] for y in good_list)]