簡體   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