Reputation: 171
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. 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. 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.
I have tried nested for loops, list comprehension (below are some examples of many failed attempts).
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
Upvotes: 2
Views: 906
Reputation: 3504
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)
. You can make it O(n log m) if you want. 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). In case the elements are hashable you can even have an O(n) solution because querying a hash-set is O(1).
Btw: The elements of both lists look like tuples to me, this will get you more close to a better solution.
Upvotes: 4
Reputation: 1836
Only the first comparison contains the not
attribute, add != to all of the comparisons and this should work:
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]]
Upvotes: 0