简体   繁体   English

如何使用字典操作字符串中每个元素的列表?

[英]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. 我希望扫描列表,并且即使字符串为C2C3C4C5,如果字符串中弹出C2C4,因为它包含C2 C4,我希望它在列表中转为1。 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: 如果C3出现在任何字符串中,那么对于C3可以说相同,那么我希望它在列表中变成1,而当C3在C3C4C5中出现时,它也应该变成1,即得到以下输出:

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: 您可以将listcomp与一个小的辅助函数一起使用:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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