繁体   English   中英

查找具有最多匹配字母的单词

[英]Find word with most matching letters

我有 2 个列表:

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

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

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

有没有办法根据l2中的字母数将l1中的值匹配到l2中?

所以 output 是:

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

这样的事情可能对你有用:

#!/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'}

我添加了“乌克兰”来测试处理模棱两可的匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM