lagn91
lagn91

Reputation: 77

Python parsing a list of strings through another list and return matches

I have two text files that I have turned into lists. List1 has lines that look like this:

'U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah'

list2 has lines that look like this:

['smuspid\n', 'USAA032367605\n', 'USAA032367776\n', 'USAA044754265\n', 'USAA044754267\n']

I want to return every line in list1 that has a match in list2. I've tried using regex for this:

found = []
check = re.compile('|'.join(list2))
for elem in list1:
    if check.match(elem):
        found.append(elem)

but my code above is returning an empty list. Any suggestions?

Upvotes: 0

Views: 50

Answers (1)

Emma
Emma

Reputation: 27723

I guess you can do that without a regular expression:

Method 1

list1 = ['U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah']

list2 = ['|USAA032812134', '|USAA0328121304', '|USAA032999812134']

found = []
for i in list1:
    for j in list2:
        if j in i:
            found.append(j)

print(found)

Output 1

['|USAA032812134']

Method 2 using List Comprehension

list1 = ['U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah']
list2 = ['|USAA032812134', '|USAA0328121304', '|USAA032999812134', 'blah']

print([j for i in list1 for j in list2 if j in i])

Output 2

['|USAA032812134', 'blah']

Method 3: strip() for new lines

You can simply strip() and append() to your found list:

list1 = ['U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah']
list2 = ['smuspid\n', 'USAA032812134\n', 'USAA032367605\n', 'USAA032367776\n',
         'USAA044754265\n', 'USAA044754267\n']

found = []
for i in list1:
    for j in list2:
        if j.strip() in i:
            found.append(j.strip())

print(found)

Output 3

['USAA032812134']

Upvotes: 2

Related Questions