[英]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]]
I have two lists of lists. 我有两个列表列表。 There are no matches between some_list and other_list for app_num.
app_um的some_list和other_list之间没有匹配项。 However, for a given app_num in other_list, the product, prod_size_ and prod_amt may be the same as in a given app_num in some_list.
但是,对于other_list中的给定app_num,product,prod_size_和prod_amt可能与some_list中给定app_num中的相同。 I am trying to create a final_some_list that is the same as some_list, except that it has deleted any list element from some_list if that list element has the same product, prod_size, and prod_amt as an element in other_list.
我正在尝试创建一个与some_list相同的final_some_list,除非它已从some_list删除任何列表元素,如果该列表元素具有相同的产品,prod_size和prod_amt作为other_list中的元素。
I have tried nested for loops, list comprehension (below are some examples of many failed attempts). 我已经尝试过嵌套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)]
Edit : 编辑 :
Solution above is O ( nm ) where n == len(some_list)
and m == len(other_list)
. 上面的解是O ( nm ),其中
n == len(some_list)
和m == len(other_list)
。 You can make it O ( n log m ) if you want. 如果需要,可以将其设为O ( n log m )。 Put all the tails of all the elements of
other_list
in a binary search tree (assuming those elements are ordable), now querying that tree is O (log m ). 将
other_list
的所有元素的所有尾部放在二叉搜索树中(假设这些元素是可以的),现在查询该树是O (log m )。 In case the elements are hashable you can even have an O ( n ) solution because querying a hash-set is O (1). 如果元素是可清除的,您甚至可以使用O ( n )解决方案,因为查询哈希集是O (1)。
Btw: The elements of both lists look like tuples to me, this will get you more close to a better solution. 顺便说一下:这两个列表的元素对我来说就像元组一样,这会让你更接近一个更好的解决方案。
Only the first comparison contains the not
attribute, add != to all of the comparisons and this should work: 只有第一个比较包含
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.