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

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

假设我有这本字典:

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

和字符串列表:

  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可能更适合作为容器):

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

试试看:

  1. lookup = {
  2. 'text_text': 1,
  3. 'text_text_num': 1
  4. }
  5. my_strings = [
  6. 'text_text_part1',
  7. 'text_text_part2',
  8. 'text_text_another_part3',
  9. 'text_text_num_something_part3'
  10. ]
  11. find(my_strings, lookup)
  12. # text_text_part1: text_text
  13. # text_text_part2: text_text
  14. # text_text_another_part3: text_text
  15. # text_text_num_something_part3: text_text_num
展开查看全部

相关问题