查找最匹配字母的单词

2024-05-19 00:40:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两份清单:

l1 = ['UK', 'GER', 'POL']

l2 = ['Germany', 'Poland', 'United Kingdom']

这些列表是指国家,但顺序不匹配

有没有办法根据l2中的字母数将l1中的值与l2中的值进行匹配

因此,输出为:

dic = {'UK': 'United Kingdom',
       'GER': 'Germany',
       'POL': 'Poland'}

Tags: l1列表顺序字母国家unitedkingdomuk
1条回答
网友
1楼 · 发布于 2024-05-19 00:40:02

像这样的东西可能适合你:

#!/usr/bin/env python3

l1 = ['UK', 'GER', 'POL']
l2 = ['Germany', 'Poland', 'United Kingdom', 'Ukraine']

d = {}
for short in l1:
    lower = short.lower()

    # Match prefix or initials.
    matches = [x for x in l2 if
               x.lower().startswith(lower) or
               ''.join(w[0] for w in x.split()).lower() == lower]

    if len(matches) == 0:
        print('no match', short)
    elif len(matches) > 1:
        print('ambiguous', short, matches)
    else:
        d[short] = matches[0]

print(d)
$ ./test.py 
ambiguous UK ['United Kingdom', 'Ukraine']
{'GER': 'Germany', 'POL': 'Poland'}

我添加了“乌克兰”来测试处理模糊匹配

相关问题 更多 >

    热门问题