Home > OS >  How to compare between lists for a partial match and create a new list from both list
How to compare between lists for a partial match and create a new list from both list

Time:04-20

I need to compare between two lists for a partial match and then create a new list based on the matching items. My current output is empty. Thanks in advance.

accounts = ['0x1212 - staff1', '0x65gs - tech01', '0x43nd - staff3', '0x89ng - tech02']
stats = ['0x1212 - (23.90)', '0x43nd - (4.70)', '0x342r - (3.76)', '0x323f - (2.76)']

data = []

for b in stats:
    if any(a.startswith(b) for a in accounts):
        data.append(b)

print (data)

Current Output:

[]

Needed Output:

Found: ['0x1212 - (23.90) - staff1, 0x43nd - (4.70) - staff3']
Not Found: ['0x65gs - tech01', '0x89ng - tech02']

CodePudding user response:

You seem to only want to look at the first 6 characters of each account. Use this:

found = []
not_found = []

for b in stats:
    for a in accounts:
        if a[:6] == b[:6]:
            found.append(b a[6:])
            break
    else:
        not_found.append(a)

print(found)
print(not_found)

CodePudding user response:

This assumes that you have - (underscore) in your strings:

result = []

for a in accounts:
    if any(b.startswith(a.split('-')[0]) for b in stats):
        result.append(a)

print("Found:", result)
print("Not Found:", list(set(accounts) - set(result)))
  • Related