Last active
May 25, 2017 08:41
-
-
Save nmpowell/4d9abd73e2671227f20965201de7dd06 to your computer and use it in GitHub Desktop.
Python snippets to check list contents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python snippets to check list contents | |
# Given two lists, A and B ... | |
# Check all the items from A are present in B: | |
set(B).issuperset(set(A)) | |
# Given a list of substrings A and another list of (longer) strings B which might contain those substrings ... | |
# e.g. | |
A = ['one', 'two', 'three'] | |
B = ['someone', 'twooo', 'trees', 'everyone'] | |
# ... list items from B which contain any of the strings in A: | |
existing = [n for n in B if any(s in n for s in A)] | |
# ['someone', 'twooo', 'everyone'] | |
# ... check at least one of each item from A is present in B (where A are substrings of items in B): | |
all(any(s in n for n in B) for s in A) | |
# False | |
# ... show which items from A are present in B: | |
[s for s in A if any(s in n for n in B)] | |
# ['one', 'two'] | |
# ... show which items from A are missing from B: | |
[s for s in A if not any(s in n for n in B)] | |
# ['three'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment