Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to have re.sub work for multiple pattern replace on list of list?

I have a list of list
input- old_list:

[['hi.','pt','patient','med',...],
['.','md','pt','md',...]...]

my desired output – new_list:

[['hi',' ',' ','medication',...],
[' ', 'medication', ' ',...]...]

and I have tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1.

adict = {"\.": " ",
        "patient": " ",
        "\bpt\b": " ",
        "\bmed\b":"medication"}
for key, value in adict.items():
    new_list= [[re.sub(key, value, e) for e in d] for d in old_list]
replacements = [('\.', ""),
                ("patient"," "),
                ("\bpt\b", " "),
                ("\bmed\b","medication")]
for old, new in replacements:
    new_list=[]
    new_list= [[re.sub(old, new, e) for e in d] for d in old_list]
  1. 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!

>Solution :

  1. You need to use output of each iteration as input for a next iteration, i.e. in new_list instead of in old_list. And of course to initialize the variable before loop: new_list = old_list.
  2. Regex patterns should have r-prefix.
  3. As mentioned in comments, avoid naming variables with built-in names like dict and list.
import re

patterns = {
    r"\.": " ",
    r"patient": " ",
    r"\bpt\b": " ",
    r"\bmed\b": "medication",
}
old_list = [['hi.', 'pt', 'patient', 'start med end'], ['.', 'md', 'pt', 'md']]

new_list = old_list
for key, value in patterns.items():
    new_list = [[re.sub(key, value, e) for e in d] for d in new_list]

print(old_list)
print(new_list)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading