首页 > 解决方案 > Python:比较字符串列表的元素,根据相似度排序

问题描述

背景

我有两个清单:

list_1 = ['a_1', 'b_2', 'c_3']
list_2 = [ 'g b 2', 'f a 1', 'h c 3']

请注意,列表中字符串元素的格式不同。换句话说,其中一个列表的元素不是另一个列表的子集。

我想要

  1. 比较列表 1 和列表 2 的元素,识别列表 2 中的元素与列表 1 相似
  2. 然后我想按照与['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']

标签: pythonstringlistcompare

解决方案


我相信有一些缺失的信息。尽管如此,对于给定的列表,我们可以设计这种方法:

# 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 已经排好序了。


推荐阅读