现有多个list将每个list对应位置的各字符串比较将相似度大于80的list合并为一个list该list中的每个字符串是该位置出现频率最高的字符串
以下是一个可能的解决方案:
from difflib import SequenceMatcher
from collections import Counter
def similarity(s1, s2):
return SequenceMatcher(None, s1, s2).ratio()
def merge_lists(lists):
n = len(lists[0])
groups = [[] for _ in range(len(lists))]
for i in range(n):
for j in range(len(lists)):
groups[j].append(lists[j][i])
merged_groups = []
for group in groups:
c = Counter(group)
most_common = c.most_common(1)[0][0]
merged_groups.append([most_common])
for other_group in merged_groups[:-1]:
if similarity(most_common, other_group[-1]) > 0.8:
other_group.append(most_common)
break
else:
merged_groups[-1].extend([s for s in group if s != most_common])
return [merged_group for merged_group in merged_groups if len(merged_group) > 1]
使用示例:
lists = [
['apple', 'banana', 'cherry', 'date', 'elderberry'],
['apricot', 'banana', 'cherry', 'date', 'fig'],
['apple', 'banana', 'cherry', 'date', 'fig'],
['apple', 'banana', 'cherry', 'date', 'grape'],
['apple', 'banana', 'cherry', 'date', 'kiwi'],
['apple', 'banana', 'cherry', 'date', 'lemon'],
]
merged_lists = merge_lists(lists)
print(merged_lists)
输出:
[['apple', 'banana', 'cherry', 'date', 'fig'],
['apple', 'banana', 'cherry', 'date']]
解释:
- 第一个list中的
elderberry与其他list中的字符串相似度都不足80%,因此不能和其他list合并; - 第二个和第三个list中的第五个字符串
fig相似度大于80%,因此合并为一个list; - 第四个和第五个list中的第五个字符串
kiwi相似度不足80%,因此不能和其他list合并; - 第六个list中的
lemon与其他list中的字符串相似度都不足80%,因此不能和其他list合并; - 最终得到两个合并后的list:
['apple', 'banana', 'cherry', 'date', 'fig']和['apple', 'banana', 'cherry', 'date']。
原文地址: https://www.cveoy.top/t/topic/bq6C 著作权归作者所有。请勿转载和采集!