2016-10-16 72 views
0

我試圖建立一個解析器現在我的代碼部分看起來像這樣的最佳方式,以匹配字典值:Python。如果條件真

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

儘管你現在的代碼工作嗎?如果roomnum =「одна」,則「один」.startswith(roomnum.lower())'不會成立。 –

+0

順便說一句,有一個更好的方法來構建這些字典,例如'字典(枚舉((「один」,「два」,「три」,「четыре」,「пять」,「шесть」,「семь」,「восемь」 ,「девять」),1))'。然而,正如Christofer Ohlsson&Nf4r所說,你可能應該交換你的鍵和值,例如枚舉({「k」,v「,」 「,」шесть「,」семь「,」восемь「,」девять「),1)}' –

回答

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] 

字典是基於keysearch,不valuesearch。第一個是O(1),當第二個是O(n)並且需要循環時,允許你使用key in dict

編輯發表評論:

,如果你想一個字映射到別人,創建另一個字典將處理它。

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

然後所有的u需要做的是:

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 
+0

非常感謝,我應該說明爲什麼我使用.startswith: –

+0

值可以通過幾種方式形成,例如: –

+0

「одна」也應該映射到「один」,是否使用for語句?順便提一下,多個評論。這是我第一次來到這裏。 –