Home > database >  How to find matching partial items from two list
How to find matching partial items from two list

Time:04-13

Good day.

I have the following 2 list that I need to compare for a match. I need to find if listB items are in listA and then return the item in listA.

listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
out = []

for b in listB:
    if any(a.startswith(b) for a in listA):
        out.append(b)

print (out)

Current Output:

['abcd754', 'abcd755', '01shdsa']

Intended Output:

['abcd754 - (32.12)', 'abcd755 - (45)' , '01shdsa - (0.01)']

CodePudding user response:

You can use assignement operator :=:

listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
out = []

for b in listB:
    if any((c := a).startswith(b) for a in listA):
        out.append(c)

print(out)

Prints:

['abcd754 - (32.12)', 'abcd755 - (45)', '01shdsa - (0.01)']

CodePudding user response:

You just need to loop over listA instead of listB.

listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
out = []

for a in listA:
    if any(a.startswith(b) for b in listB):
        out.append(a)

print (out)

#['abcd755 - (45)', 'abcd754 - (32.12)', '01shdsa - (0.01)']
  • Related