2

I have two lists of lists, one that includes all records e.g. [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']] and one that contains rules [['milk', 'eggs'], ['milk','ham']].

I'm trying to filter records by the list_of_rules, however, I want to capture [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']] despite it not exactly matching [['milk', 'eggs'], ['milk','ham']] order and extra items wise.

records = [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]

list_of_rules = [['milk', 'eggs'], ['milk','ham']]

# this list comprehension only filters for exact matches

results = [[x for x in L if x in records] for L in list_of_rules] 


# expected output

print(results)
>>[['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']]

Any and all recommendations very much appreciated.

0

2 Answers 2

1

You can use this list comprehension:

records = [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]

list_of_rules = [['milk', 'eggs'], ['milk','ham']]

results = [L for L in records if any(set(R).issubset(L) for R in list_of_rules)]

print(results) # => [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']]

It loops for each list of records L and checks whether there exists at least one list of rules R (using the built-in function any) such that R is included in L (using the set method issubset).

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

Comments

0

You can use a list of sets of rules and demand that any rule intersection'ed with a inner list is identical to the set (i.e. all items in the set are also present in the inner list):

records = [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]

list_of_rules = [{'milk', 'eggs'}, {'milk','ham'}]

# this list comprehension only filters for exact matches

# take the full inner list if all things in any rule are in this inner list
results = [ x for x in records if any( p.intersection(x) == p for p in list_of_rules)  
print(results)

Output:

[['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']]

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.