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

Compare 2 lists and output the similar matches

I have 2 Python lists :

prefixList = ["12","9"]

files = ["12-a.csv","12-b.csv","9-t.txt","8-a.txt"]

and want to create a new list with a list of files that start with the prefix list, so the output will be:

fileOutput = ["12-a.csv","12-b.csv","9-t.txt"]

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

>Solution :

You can use regex and find number and search number in prefixList.

prefixList = ["12","9"]

files = ["12-a.csv","12-b.csv","9-t.txt","8-a.txt"]

new_files = [file 
             for file in files 
             if(re.search(r'\d+', file).group(0) in prefixList)]

print(new_files)

Output:

['12-a.csv', '12-b.csv', '9-t.txt']
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