I have a list of list input- old_list:
JavaScript
x
3
1
[['hi.','pt','patient','med', ],
2
['.','md','pt','md', ] ]
3
my desired output – new_list:
JavaScript
1
3
1
[['hi',' ',' ','medication', ],
2
[' ', 'medication', ' ', ] ]
3
and I have tried
1.
JavaScript
1
5
1
adict = {".": " ",
2
"patient": " ",
3
"bptb": " ",
4
"bmedb":"medication"}
5
JavaScript
1
3
1
for key, value in adict.items():
2
new_list= [[re.sub(key, value, e) for e in d] for d in old_list]
3
JavaScript
1
5
1
replacements = [('.', ""),
2
("patient"," "),
3
("bptb", " "),
4
("bmedb","medication")]
5
JavaScript
1
4
1
for old, new in replacements:
2
new_list=[]
3
new_list= [[re.sub(old, new, e) for e in d] for d in old_list]
4
- and
replace(new_list, old, new) for ...
but none of them works, the output is the same as the original old_list. Any suggestions? Thanks!
Advertisement
Answer
- You need to use output of each iteration as input for a next iteration, i.e.
in new_list
instead ofin old_list
. And of course to initialize the variable before loop:new_list = old_list
. - Regex patterns should have
r
-prefix. - As mentioned in comments, avoid naming variables with built-in names like
dict
andlist
.
JavaScript
1
17
17
1
import re
2
3
patterns = {
4
r".": " ",
5
r"patient": " ",
6
r"bptb": " ",
7
r"bmedb": "medication",
8
}
9
old_list = [['hi.', 'pt', 'patient', 'start med end'], ['.', 'md', 'pt', 'md']]
10
11
new_list = old_list
12
for key, value in patterns.items():
13
new_list = [[re.sub(key, value, e) for e in d] for d in new_list]
14
15
print(old_list)
16
print(new_list)
17