Skip to content
Advertisement

how to match two lists that contain some matching strings?

I have two list such as. First list contains some additional string in the elements but I want to find the match with or without converting it to integer from the second list.

 l1 = ['1a','2','3','1b']
 l2 = ['1a','4']

output req:

output_requried = ['1a', '1b'] #I need all match that contains 1

Tried:

[x for x in l1 if any(y in x for y in l2)] 
# It doesn't print "1b", but it can work with ['1','4']

Advertisement

Answer

If you only want to compare the number part you have to do some conversion.

Start with

l1 = ['1a','2','3','1b']
l2 = ['1a','4']
l2 = [int(''.join(c for c in value if c.isdigit())) for value in l2]
print(l2)

l2 is now [1, 4].

Now we use a list comprehension to create our match. We loop over every value in l1, take only the digits from the value (as we did while redefining l2), convert them to an integer and check if they are in l2.

match = [value for value in l1 if int(''.join(c for c in value if c.isdigit())) in l2]
print(match)

This gives us ['1a', '1b'].


Using a function for the conversion might help understanding the code and makes sure that the values are treated the same.

def get_int_value(value):
    return int(''.join(c for c in value if c.isdigit()))

l1 = ['1a','2','3','1b']
l2 = ['1a','4']
l2 = [get_int_value(value) for value in l2]
match = [value for value in l1 if get_int_value(value) in l2]
print(match)

This is a simple approach, so a value like "1a2b3" might or might not be treated as you want. You dind’t specify this in the question.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement