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.

JavaScript

output req:

JavaScript

Tried:

JavaScript

Advertisement

Answer

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

Start with

JavaScript

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.

JavaScript

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.

JavaScript

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