简体   繁体   中英

How to use a dictionary to manipulate a list per element within a string?

I have a list and a dictionary of:

list1 = ['C1','C1C2C3C4','C3C4C5','C2C4C5']
dict1 = {'C2C4':1, 'C3':1}

I want the list to be scanned and if C2C4 pops up within the string even if the string is C2C3C4C5, as it contains a C2 AND a C4, I want it to turn to a 1 within the list. Same can be said for C3 if C3 appears in any of the strings then I want it to turn to a 1 within the list and as a C3 turns up in C3C4C5 then this should also turn to a 1 ie to get an output of:

list1 = [0,1,1,1]

I've been using this method from what I found on this site:

result = [(lambda x:0 if not x else min(x))([b for a, b in dict1.items() if i in a]) for i in list1]

But this doesn't work for this scenario as it won't pick up different components within the string and so outputs:

Results = [0, 0, 0, 0]

........can someone help?

You can use a listcomp with a small helper function:

import re

list1 = ['C1', 'C1C2C3C4', 'C3C4C5', 'C2C4C5']
dict1 = {'C2C4': 1, 'C3': 1}

def func(s):
    for k, v in dict1.items():
        if all(i in s for i in re.findall('\w\d', k)):
            return v
    else:
        return 0

[func(i) for i in list1]
# [0, 1, 1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM