'python trying to match 1 list partially with an other list

I've got 2 list with data in it and I want to match the first list with the second one.

in my second list the data contain's the first list and some other data as one object.

the lists

list_1 = [
    'id1',
    'id2'
]

list_2 = [
    'a815-8d4a  -- id5',
    'aba2-a6ac  -- id5',
    'e7f0-efbf  -- id1'
]

the output I'm looking for is that there is a new list created or that list_2 is filtered to look like this

x = ['e7f0-efbf']

I have tried to use any with for loops like below but it only matches the full id in 2nd list.

q = [i for i in list_1 if any(i for j in list_2 if str(j) in i)]
print(q)


Solution 1:[1]

This code might work, assuming you search for the code associated with each id in the second list(if my interpretation is wrong please correct me):

list_1 = [
    'id1',
    'id2'
]

list_2 = [
    'a815-8d4a  -- id5',
    'aba2-a6ac  -- id5',
    'e7f0-efbf  -- id1'
]
x = []
for i in list_1:
    for j in list_2:
        if j.find(i)>-1:
            x.append(j[:j.find(i)-5])
            
print(x)

Solution 2:[2]

Let's make an assumption here - i.e., that the strings in list_2 each contain at least two whitespace delimited tokens and that each token is of indeterminate length.

Therefore we can use a list comprehension as follows:

result = [v for v, *_, k in map(str.split, list_2) if k in list_1]
print(result)

...which gives us...

['e7f0-efbf']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anshumaan Mishra
Solution 2 Albert Winestein