python - Python:比较字符串列表的元素,根据相似度排序
问题描述
背景
我有两个清单:
list_1 = ['a_1', 'b_2', 'c_3']
list_2 = [ 'g b 2', 'f a 1', 'h c 3']
请注意,列表中字符串元素的格式不同。换句话说,其中一个列表的元素不是另一个列表的子集。
我想要
- 比较列表 1 和列表 2 的元素,识别列表 2 中的元素与列表 1 相似
- 然后我想按照与
['b_2', 'a_1', 'c_3']
列表 2 相同的顺序对列表 1 进行排序
现有问题
还有其他几个关于列表比较的问题,但其中大多数比较相似的字符串。
实际清单
list_1 = ['f_Total_water_withdrawal',
'f_Precipitation',
'f_Total-_enewable_water_resources',
'f_Total_exploitable_water_resources',]
list_2 = ['Precipitation',
'Total-renewable-water-resources',
'Total exploitable water resources',
'Total water withdrawal']
解决方案
我相信有一些缺失的信息。尽管如此,对于给定的列表,我们可以设计这种方法:
# 1. Format list 2 to look like list 1
list_2_mod = [s[2:].replace(" ", "_") for s in list_2]
# 2. Filter elements in list 2 not in list 1
list_final = [s for s in list_2_mod if s in list_1]
明智的做法是,鉴于您的 list_1(具有唯一元素,并且所有元素在 list_2 中具有明显等效项),您只需要第一步。无需排序!list_2 已经排好序了。
推荐阅读
- python - 如何在 Django 管理界面中显示腌制集?
- reference - 如果指定了 OutputPath,为什么 MSBuild 会忽略 ProjectReference Private=False
- swift - 使用 SwiftUI 绘制形状
- ubuntu - 如何在 RockPiX 板上配置 SPI?
- python - 如何修复“密钥(用户名)=()已存在。” 错误
- vba - 第一次执行后VBA中的慢循环,如果我使用“STOP”又快了
- c# - 给定方法的有序执行,因为它们没有按顺序被解雇
- java - Hibernate Envers:暂时禁用审计
- centering - Lavaan 中的多级中介,变量居中
- latex - 在使用 LaTeX 学习英语语法中标记主语 (S) 和动词 (V)