Python - 比较两个嵌套列表并写入第三个嵌套列表
问题描述:
some_list = [[app_num, product, prod_size, prod_amt]]
other_list = [[app_num, product, prod_size, prod_amt]]
我有两个列表。 app_num的some_list和other_list之间没有匹配。但是,对于other_list中的给定app_num,产品prod_size_和prod_amt可能与some_list中给定app_num中的相同。我正在尝试创建一个与some_list相同的final_some_list,除了它已从some_list中删除任何列表元素(如果该列表元素具有相同的product,prod_size和prod_amt作为other_list中的元素)。Python - 比较两个嵌套列表并写入第三个嵌套列表
我已经尝试嵌套for循环,列表理解(下面是许多失败尝试的一些例子)。
final_some_list = [app for app in some_list for other_app in other_list
if not app[1] == other_app[1] and app[2] == other_app[2] and app[3] ==
other_app[3]
final_some_list = [app for app in some_list for other_app in other_list
if not app[1] and app[2] and app[3] == in other_app
答
final_some_list = [x for x in some_list if all(x[1:] != y[1:] for y in other_list)]
+0
非常优雅,谢谢! – vintagedeek
答
只有第一个比较包含not
属性,添加=所有的比较,而这应该工作:
final_some_list = [app for app in some_list for other_app in other_list
if app[1] != other_app[1] and app[2] != other_app[2] and app[3] !=
other_app[3]]
你能分享输入的实例和期望的输出,使它让任何人都更容易理解你的问题? –