python 如何在子字符串列表中找到精确的子字符串?

mgdq6dx1  于 2023-03-28  发布在  Python
关注(0)|答案(1)|浏览(121)

假设我有这本字典:

lookup = {"text_text": 1, "text_text_num": 1}

和字符串列表:

my_strings = ["text_text_part1", "text_text_part2", "text_text_another_part3", "text_text_num_something_part3"]

如何确保my_strings[0]my_strings[1]my_strings[2]只与lookup中的text_text匹配,而my_strings[3]text_text_num匹配?后缀是动态的,我无法从字符串中正则化所需的部分,因为我不知道它们何时停止。

polkgigr

polkgigr1#

假设lookup的键是从最短到最长排序的(也就是说,list可能更适合作为容器):

def find(my_strings, lookup):
  for string in my_strings: # For each string
    matched = None
    
    for word in lookup:     # Check all words
      if word in string:    # If a match is found
        matched = word      # Assign to matched, even if it already has a non-None value
    
    print(f'{string}: {matched}')

试试看:

lookup = {
    'text_text': 1,
    'text_text_num': 1
}

my_strings = [
    'text_text_part1',
    'text_text_part2',
    'text_text_another_part3',
    'text_text_num_something_part3'
]

find(my_strings, lookup)
# text_text_part1: text_text
# text_text_part2: text_text
# text_text_another_part3: text_text
# text_text_num_something_part3: text_text_num

相关问题