如何实现从字符串列表中筛选唯一匹配答案的Python函数?
需求与问题分析
需求说明
我有两个列表:
texts = ["this is string 1", "this is string 2", "this is string 3"] answers = ["this", "string 1", "string 3"]
需要编写一个函数,从answers中返回尽可能多的答案(及其对应文本),满足要求:
- 每个返回的答案仅在返回的文本中的某一个里存在(精确字符串匹配),即每个返回的答案必须仅出现在一个被选中返回的文本中。
- 函数返回格式为列表的列表,每个子列表是
[answer, corresponding text]。
示例说明
示例一
针对开头的列表,"string 1"只在第一个文本"this is string 1"中出现,"string 3"只在最后一个文本"this is string 3"中出现,这两个符合要求;而"this"出现在所有文本里,因此不返回。最终结果应为[['string 1', 'this is string 1'], ['string 3', 'this is string 3']]。
示例二
当列表改为:
texts = ["this is string 1 this is string 2", "this is string 1", "this is string 3"] answers = ["this", "string 1", "string 3"]
合法的返回结果有两种:
[["string 1", "this is string 1"],["string 3", "this is string 3"]]
或者:
[["string 1", "this is string 1 this is string 2"],["string 3", "this is string 3"]]
因为"string 1"在选中的返回文本里只出现一次(要么选第二个文本,要么选第一个,都不会和"string 3"所在的第三个文本冲突)。
当前代码与问题
我写的代码如下:
def find_unique_answers(texts, answers): result = [] for answer in answers: text_found = None for text in texts: if answer in text: if text_found is None: text_found = text else: text_found = None break if text_found is not None: result.append([answer, text_found]) return result # 示例一测试 texts = ["this is string 1", "this is string 2", "this is string 3"] answers = ["this", "string 1", "string 3"] output = find_unique_answers(texts, answers) print(output) # 输出符合预期:[['string 1', 'this is string 1'], ['string 3', 'this is string 3']]
但用示例二的列表测试时,输出结果是[['string 3', 'this is string 3']],不符合预期,想知道问题出在哪里。
内容的提问来源于stack exchange,提问作者Penguin
相关产品推荐
相关产品推荐

