Home > database >  How to compare items among 3 lists
How to compare items among 3 lists

Time:04-13

I am trying to add comparison among 3 lists. listB is compared to listA and then listA is compared to listC to create a new combined items.

listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
listC = ['abcd755 - staff1', 'abcd754 - staff2', '3xas34a - demo1', '01shdsa - staff3', '23xas34a - demo2']

out = []

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

print(out)

Current Output: # comparing 2 list

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

Output Needed: # a combination of data from amonglists

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

CodePudding user response:

# your code goes here
listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
listC = ['abcd755 - staff1', 'abcd754 - staff2', '3xas34a - demo1', '01shdsa - staff3', '23xas34a - demo2']
from collections import defaultdict as dd

out = dd(list)
for i in listA:
    a, b = i.split(' - ')
    out[a].append(b)

for i in listC:
    a, b = i.split(' - ')
    if a in out:
        out[a].append(b)

result = []
for i in listB:
    if i in out:
        result.append(' - '.join([i, *out[i]]))
print(result)

output

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

CodePudding user response:

Your listA and listC are effectively key-value pairs, so you could convert them to dictionaries and then look up their values for the entries in listB:

dict_a = dict(n.split(" - ", maxsplit=1) for n in listA)
dict_c = dict(n.split(" - ", maxsplit=1) for n in listC)

for b in listB:
    if b in dict_a and b in dict_c:
        out.append(f"{b} - {dict_a[b]} - {dict_c[b]}")

>>> out
# ['abcd754 - (32.12) - staff2',
#  'abcd755 - (45) - staff1',
#  '01shdsa - (0.01) - staff3']
  • Related