如何用Python实现文本匹配?编写的代码无法运行求帮助
问题解决
你的代码逻辑有误:list1里的是标识(比如example1),list2里是对应文本,这两个列表的元素完全不重合,if a in list2这个判断永远不会成立,所以没法输出预期内容。
实现方式一:直接按对应位置匹配输出
如果两个列表的元素是一一对应的(list1的第n个元素对应list2的第n个文本),用zip函数打包后遍历即可:
list1 = ['example1', 'example3', 'example2'] list2 = ['text of example 1', 'text of example 3', 'text of example 2'] for key, text in zip(list1, list2): print(f"{key} = {text}")
输出结果:
example1 = text of example 1 example3 = text of example 3 example2 = text of example 2
实现方式二:按标识顺序排序输出
如果需要输出按example1、example2、example3的顺序排列,先把两个列表转成字典建立映射,再对键排序后输出:
list1 = ['example1', 'example3', 'example2'] list2 = ['text of example 1', 'text of example 3', 'text of example 2'] # 构建标识与文本的映射字典 mapping = dict(zip(list1, list2)) # 对标识排序后输出 for key in sorted(mapping): print(f"{key} = {mapping[key]}")
输出结果:
example1 = text of example 1 example2 = text of example 2 example3 = text of example 3
内容的提问来源于stack exchange,提问作者Inj3ct0r
相关产品推荐
相关产品推荐

