-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilterListGivenSubstringList
More file actions
37 lines (30 loc) · 1.55 KB
/
FilterListGivenSubstringList
File metadata and controls
37 lines (30 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Python3 program to Filter or Filter Out
# list of strings based on another list
# taken from website : https://www.geeksforgeeks.org/python-filter-list-of-strings-based-on-the-substring-list/?ref=rp
def Filter(string, substr):
return [str for str in string if
any(sub in str for sub in substr)]
# taken from website : https://www.geeksforgeeks.org/python-filter-a-list-based-on-the-given-list-of-strings/?ref=rp
def FilterOut(string, substr):
return [str for str in string if
all(sub not in str for sub in substr)]
# Regular Expression codes referenced from website : https://www.educative.io/edpresso/how-to-implement-wildcards-in-python
# Regular expression library
import re
# Similar to Filter, but utilizing list with Regular Expressions as substring
def FilterRegEx(string, substr):
return [str for str in string if
any(re.search(sub, str) for sub in substr)]
# Similar to FilterOut, but utilizing list with Regular Expressions as substring
def FilterOutRegEx(string, substr):
return [str for str in string if
all(not re.search(sub, str) for sub in substr)]
# Sample List initializations
string = ['city1', 'class5', 'room2', 'city2']
substr = ['class', 'city']
substrRegEx = ['cit.+', 'class.']
# Driver code
print(Filter(string, substr)) # Output : ['city1', 'class5', 'city2']
print(FilterOut(string, substr)) # Output : ['room2']
print(FilterRegEx(string, substrRegEx)) # Output : ['city1', 'class5', 'city2']
print(FilterOutRegEx(string, substrRegEx)) # Output : ['room2']