如何使用字典扫描列表中的部分外观?

2024-06-10 11:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用字典扫描字符串列表,看看它是否出现在字符串中例如,假设我有一个{C99':1,'C4':1}的字典,它的列表是['C99C2C3C5','C88C4'],那么新的列表将是['1',“1”],因为“C99”出现在字符串“C99C2C3C4”中,“C4”出现在“C88C4”中。你知道吗

我目前的做法是:

import re

dict = {'C99': 1,'C15':1}
ComponentList = ['C1C15C99', 'C15', 'C17']

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

ComponentList = [func(i) for i in ComponentList]

输出:

[1, 1, 1]

想要的输出:

[1,1,0]

为了澄清,如果这是我的系统:

my_dict = {'C1C55C99': 1, 'C17': 1, 'C3': 1}
component_list = ['C1C15C55C99', 'C15', 'C17']

因为'C1C55C99'出现在'C15C55C99'中,我希望该值更改为字典值以提供输出:

results = ['1','0','1']

但是,当组件号超过C9时,这个方法就不起作用了,我希望有人能帮我解决这个问题,这样就可以对Cx起作用,并解释为什么以前的方法不起作用。你知道吗

谢谢,本


Tags: 字符串inre列表forreturn字典dict
3条回答

从您在这里的评论来看,在我看来,组件列表中的字符'C'很重要,因为您似乎想区分'C11''C1'。你知道吗

顺便说一句,我完全同意@martineau在python中始终使用标准命名。CamleCasingLikeThis应该只保留给类名,一般情况下应该对变量使用lower_case_like_this,而不是大写。你知道吗

让我们来看看如何做到这一点。你知道吗

my_dict = {'C99': 1, 'C15': 1, 'C1': 1}
component_list = ['C1C15C99', 'C15', 'C17']

result = []

# first convert my_dict to a list of numbers ['99', '15', '1']
elements = [element[1:] for element in my_dict.keys()]

# for every component you want to characterize
for component in component_list:

    # a flag to know if we found any element in this component
    found = False

    # split the string by the 'C' character to get its sub element numbers
    # for example 'C1C15C99'.split('C') == ['', '1', '15', '99']
    for sub_elem in component.split('C'):

        # make sure sub_elem is not an empty string
        if sub_elem:

            # check if this sub element exists in elements
            if sub_elem in elements:

                found = True

                # exit the inner loop
                break

    # convert the boolean to int (either 0 or 1)
    # and finally add this to the result
    result.append(int(found))

print(result)
# [1, 1, 0]

到目前为止,我一直假设my_dict只能采用像C1或C6这样的单数成分,而不能采用像C12C14这样的复合物。从您最近的comment来看,情况似乎并非如此。还有两件事突然变得很清楚:my_dict可以包含组件的组合,当检查一个组件是否存在于另一个组件中时,顺序并不重要。例如,C5C2C7C1中存在C1C2,但C1C2不存在,因为两个子成分都必须存在。你知道吗

这是非常重要的,它完全改变了问题。请务必从一开始就详尽地描述您的问题,以供将来参考。你知道吗

my_dict = {'C99': 1, 'C15': 1, 'C1': 1, 'C1C55C99': 1, 'C99C6': 1, 'C2C4C18': 1}
component_list = ['C1C15C99', 'C15', 'C17', 'C8C6C80C99', 'C6', 'C55C2C4C18C7', 'C55C1', 'C18C4']

result = []

# first convert my_dict to a list of lists containing singular elements
elements = [element.split('C')[1:] for element in my_dict.keys()]
# elements = [['2', '4', '18'], ['99'], ['1'], ['15'], ['99', '6'], ['1', '55', '99']]

for component in component_list:

    found = False

    # gather the sub elements for this components
    comp_elements = component.split('C')[1:]

    for composite_element in elements:

        element_exists = True

        # check if every singular element in this element is present in component
        for signular_element in composite_element:

            if signular_element not in comp_elements:
                element_exists = False
                break

        if element_exists:
            found = True
            break

    result.append(int(found))

print(result)
# [1, 1, 0, 1, 0, 1, 1, 0]

我不擅长一行程序,但它比你的简单得多,而且不需要使用regex,只需使用if x in y

def func(s):
for k, v in dict.items():
    if k in s:
        return v
return 0

根据对你的问题和评论的编辑,我想我(终于)明白你想做什么了,所以这是我的实质性修改的答案。你知道吗

我认为显示的代码可以经受一点改进/优化,但首先需要确认它现在做的是正确的事情。你知道吗

import re

def func(comps):
    pats = [c for c in re.findall(r'\w\d+', comps)]

    for k, v in my_dict.items():
        if any(p in k for p in pats):
            return v

    return 0

# Testcases

my_dict = {'C99': 1, 'C4': 1}
components_list =  ['C99C2C3C5', 'C88C4']
result = [func(comps) for comps in components_list]
print('result:', result)  # -> result: [1, 1]

my_dict = {'C99': 1,'C15': 1}
components_list = ['C1C15C99', 'C15', 'C17']
result = [func(comps) for comps in components_list]
print('result:', result)  # -> result: [1, 1, 0]

my_dict = {'C1C55C99': 1, 'C17': 1, 'C3': 1}
components_list = ['C1C15C55C99', 'C15', 'C17']
result = [func(comps) for comps in components_list]
print('result:', result)  # -> result: [1, 0, 1]

注意:您真的不应该将变量命名为与Python内置相同的名称,比如dict,因为这很混乱,除非您非常小心(或者只是运气好)。你知道吗

一般来说,我建议遵循PEP 8 - Style Guide for Python Code,特别是Nnaming Conventions部分,这也需要将ComponentList改成小写单词,由"_"字符分隔,在这种情况下,components_list将符合指南。你知道吗

相关问题 更多 >