Search code examples
pythonpython-3.xlistpattern-matchingstartswith

Check whether a list starts with the elements of another list and if found return both the values together


I have 2 lists:

substance = ['HYDROCHLORIC ACID 2M', 'ROPIVACAINE HYDROCHLORIDE MONOHYDRATE', 'SODIUM CHLORIDE', 'SODIUM HYDROXIDE 2M', 'WATER FOR INJECTIONS']

extracteddata = ['Ropivacaine hydrochloride monohydrate for injection (corresponding to 2 mg Ropivacaine hydrochloride anhydrous) 2.12 mg Active ingredient Ph Eur ', 'Sodium chloride for injection 8.6 mg Tonicity contributor Ph Eur ', 'Sodium hydroxide 2M q.s. pH-regulator Ph Eur, NF Hydrochloric acid 2M q.s. pH-regulator Ph Eur, NF ', 'Water for Injections to 1 ml Solvent Ph Eur, USP The product is filled into polypropylene bags sealed with rubber stoppers and aluminium caps with flip-off seals. The primary container is enclosed in a blister. 1(1)']

I want to check which element of extracteddata starts with which element of substance and return them together.

Expected output:

matchedlist = [substance:'ROPIVACAINE HYDROCHLORIDE MONOHYDRATE',extracteddata:'Ropivacaine hydrochloride monohydrate for injection (corresponding to 2 mg Ropivacaine hydrochloride anhydrous) 2.12 mg Active ingredient Ph Eur'],[substance:'SODIUM HYDROXIDE 2M', extracteddata:'Sodium hydroxide 2M q.s. pH-regulator Ph Eur, NF Hydrochloric acid 2M q.s. pH-regulator Ph Eur, NF ']

and likewise...

Anyhelp regarding this


Solution

  • This is a possible solution:

    result = []
    for s in substance:
        for e in extracteddata:
            if e.upper().startswith(s.upper()):
                result.append([s, e])
    print(result)