2
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
1
  • 1
    Can you share an example of input and desired output so that it makes easier for anyone to understand your question? Commented Sep 23, 2017 at 0:36

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

Comments

0

Only the first comparison contains the notattribute, 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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.