[英]Generate a nested list of 0's and 1's by comparing two nested lists in python
[英]Python - comparing two nested lists and writing a third nested list
some_list = [[app_num, product, prod_size, prod_amt]]
other_list = [[app_num, product, prod_size, prod_amt]]
我有两个列表列表。 app_um的some_list和other_list之间没有匹配项。 但是,对于other_list中的给定app_num,product,prod_size_和prod_amt可能与some_list中给定app_num中的相同。 我正在尝试创建一个与some_list相同的final_some_list,除非它已从some_list删除任何列表元素,如果该列表元素具有相同的产品,prod_size和prod_amt作为other_list中的元素。
我已经尝试过嵌套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)]
编辑 :
上面的解是O ( nm ),其中n == len(some_list)
和m == len(other_list)
。 如果需要,可以将其设为O ( n log m )。 将other_list
的所有元素的所有尾部放在二叉搜索树中(假设这些元素是可以的),现在查询该树是O (log m )。 如果元素是可清除的,您甚至可以使用O ( n )解决方案,因为查询哈希集是O (1)。
顺便说一下:这两个列表的元素对我来说就像元组一样,这会让你更接近一个更好的解决方案。
只有第一个比较包含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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.