我正在尝试使用字典来扫描字符串列表,以查看它是否完全出现在字符串中,例如,假设我有一个{'C99':1,'C4':1}字典,其中包含['C99C2C3C5','C88C4'],则新列表将为['1','1'],因为在字符串'C99C2C3C4'中出现了'C99',而在'C88C4'中出现了'C4'。
我目前这样做的方法是:
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'出现在'C1C15C55C99'中,所以我希望将值更改为字典值以提供输出:
results = ['1','0','1']
但是,当组件编号超过C9并希望有人可以帮助我解决问题时,此方法将不起作用,因此它可以用于Cx,并解释为什么以前的方法不起作用。
谢谢本
最佳答案
从您的评论看来,在我看来组件列表中的字符'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
可以包含一个组件的组合,并且当检查一个组件是否存在时,顺序无关紧要。例如,C1C2确实存在于C5C2C7C1中,但C1C2不存在于C1中,因为两个子组件都必须存在。这非常重要,它可以彻底改变问题。为了将来参考,请确保从一开始就详尽地描述您的问题。
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]
关于python - 如何使用字典扫描列表的部分外观?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54963906/