python – Comparing two lists to find elements that match the rules

Question:

The question is, for example, I have two lists:

lst1 = ['1', '2' , '3' , '4']
lst2 = ['123', '234' , '345' , '334']

How can I find such elements in the second list, which include only those elements that are in the first, but if there is one unit in the first list, then for example the element "112" from the second list is not suitable.

That is, the result of the program should be

ls3 = ['123', '234']

'345' – did not fit because there is an element "5" which is not in the first list

'334' – did not fit because there are two "3" elements, and in the first list there is only one "3" element

Answer:

This problem can be solved by using the standard class for the Counter multiset:

from collections import Counter

lst1 = ['1', '2' , '3' , '4']
lst2 = ['123', '234' , '345' , '334']

base = Counter(lst1)
result = [s for s in lst2 if not (Counter(s) - base)]

The not (Counter(s) - base) condition checks that the multiset s no more elements than the base

Scroll to Top