[英]List comprehension on lists within lists
如果我创建两个包含这样的列表的列表:
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中的item打印内容时,得到的内容如下:
yellow_widget
smells_bad
10
任何线索将不胜感激。
一支班轮
[x for x in bad_list if any(x[0] == y[0] for y in good_list)]
*感谢@Bakuriu
并未通过任何方式进行真正的优化,但这应该可以工作: 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]]
尝试这个:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.