蟒蛇。如果条件为真,则匹配字典值的最佳方法

时间:2016-10-16 11:55:55

标签: python dictionary

我正在尝试构建一个解析器,现在我的代码的一部分看起来像这样:

    azeri_nums      = {k:v for k,v in zip(range(1,10),("bir","iki","uc","dord","beş","altı","yeddi","səkkiz","doqquz"))}
russian_nums    = {k:v for k,v in zip(range(1,10),("один","два","три","четыре","пять","шесть","семь","восемь","девять"))}

想象一下,如果roomnum =“одна”,我应该找到数字 以下是我尝试匹配的方法:

    if roomnum.isalpha():
    for key,value in azeri_nums.items():
        if value.startswith(roomnum.lower()):
            roomnum = str(key)
            break

if roomnum.isalpha():
    for key,value in russian_nums.items():
        if value.startswith(roomnum.lower()):
            roomnum = str(key)
            break

有没有其他方法可以更快地运行,或者针对这种情况采取一些最佳做法?

提前谢谢!

P.S。 这个代码工作的原因是“重新”从“одна”只捕获“од”,这就是“один”.startswith(“од”)返回true的原因。

1 个答案:

答案 0 :(得分:1)

将你的词典更改为

azeri_nums = {v.lower():k for k,v in zip(range(1,10),("bir","iki","uc","dord","beş","altı","yeddi","səkkiz","doqquz"))}
russian_nums  = {v.lower():k for k,v in zip(range(1,10),("один","два","три","четыре","пять","шесть","семь","восемь","девять"))}

一旦你的名字映射到数字,只需使用:

key = None # By default
roomnum_lower = roomnum.lower()
if roomnum_lower in azeri_nums:
    key = azeri_nums[roomnum_lower]
elif roomnum_lower in russian_nums:
    key = russian_nums[roomnum_lower]

Dictionary基于keysearch,而不是valuesearch。第一个是O(1),当第二个为O(n)时,允许你使用key in dict,并且需要循环。

编辑评论:

如果你想将一个单词映射到其他单词,请创建另一个单词来处理它。

 string_map = {'одна': ['один',]} # map single string to many others if u want

然后你需要做的就是:

key = None # By default
roomnum_lower = roomnum.lower()
if roomnum_lower in azeri_nums:
    key = azeri_nums[roomnum_lower]
elif roomnum_lower in russian_nums:
    key = russian_nums[roomnum_lower] 
if key is None:
    # At this point you know that the single string is not in any dict,
    # so u start to check if any other string that u assigned to it is in dict
    for optional_string in string_map.get(roomnum_lower, []):
        opt_str_low = optional_string.lower()
        key = azeri_nums.get(opt_str_low, None)
        key = russian_nums.get(opt_str_low, None) if key is None else key