+6 votes
1 view
in Python by (28.7k points)

I want to create a new list from the existing two lists that will have all the matches from list 2 which has an exact string match in list 1

My two lists are:

a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']

b = ['rtvg', 'D4Q']

Output desired:-

list3=['rtvg_c1.4.doc', 'D4Q_d1.8.ppt']

The Code that I have used:

import csv

import os

import re

metadata = []

with open('D:/meta_demo.csv', 'r') as f:

   rows = csv.reader(f)

   for i in rows:

       metadata.append(i)

       #print(i)    

b= metadata[1:20]

DIR = 'D:/abc_file/'

a = [i for i in os.listdir(r"D:\abc_file")]

list3 = []

for i in a:

   if re.search(r"[^_]*", i) in b:

       list3.append(a)

list3 = [i for i in b if re.search(r"[^_]*", i) in a]

1 Answer

0 votes
by (68.3k points)
edited by

There are few ways of doing this problem which I am sharing here:

  • We can simply use string function startwith() to do this problem

     Syntax for this is:

str.startwith(prefix[,start[,  end]])

Prefix will be any string or tuple of string to be checked while start and end will be optional

a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']

b = ['rtvg', 'D4Q']

 result = [i for i in a if i.startswith(tuple(b))]

print(result)

output:-['rtvg_c1.4.doc', 'D4Q_d1.8.ppt']

  • Second way is to use regular expression to solve this problem.

import re

a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']

b =['rtvg', 'D4Q']

pattern = re.compile("|".join(b))

result = [i for i in a if pattern.match(i)]

print(result)

output:-['rtvg_c1.4.doc', 'D4Q_d1.8.ppt']

  • We have other approaches for matching as well if we want to find strings that is common in both the list. For this we will use set method which is best to do

a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']

b = ['rtvg_c1.4.doc', 'D4Q']

set(a) & set(b)

output:-{'rtvg_c1.4.doc'}

You can have a look at the following video tutorial to know clear all your doubts:-

...