2014-09-03 18 views
0

大家好,我用一個函數和循環編寫了下面這個簡單的翻譯程序,但是我試圖更好地理解列表理解/高階函數。我對map和listcomprehensions等函數有一個非常基本的把握,但是當循環需要佔位符值(如place_holder)在下面的代碼中時,不知道如何使用它們。此外,任何建議,我可以做得更好,將不勝感激。在此先感謝,你們搖滾!如何使用python將此函數/ for循環轉換爲列表comprehensionor高階函數?

P.S你是如何得到那個我發佈的代碼看起來像它在記事本++中的花哨格式?

sweedish = {'merry': 'god', 'christmas': 'jul', 'and': 'och', 'happy':'nytt','year':'ar'} 
    english =('merry christmas and happy new year') 
    def translate(s): 
     new = s.split() #split the string into a list 
     place_holder = [] #empty list to hold the translated word 
     for item in new: #loop through each item in new 
      if item in sweedish: 
       place_holder.append(sweedish[item]) #if the item is found in sweedish, add the corresponding value to place_holder 
     for item in place_holder: #only way I know how to print a list out with no brackets, ' or other such items. Do you know a better way? 
      print(item, end=' ') 
    translate(english) 

編輯顯示chepner答案,並chisaku的格式提示:

sweedish = {'merry': 'god', 'christmas': 'jul', 'and': 'och', 'happy':'nytt','year':'ar'} 
english =('merry christmas and happy new year') 
new = english.split() 
print(' '.join([sweedish[item] for item in new if item in sweedish])) 
+0

精美的代碼突出顯示已經存在於您的問題中,但正確的語法是縮進4個空格的任何文本塊將被視爲代碼塊,渲染時會觸發語法高亮顯示器。 – rennat 2014-09-03 16:04:33

+0

我現在看到它,它沒有出現之前.. – 2014-09-03 16:24:25

回答

1

列表理解只是建立一個列表中的所有一次,而不是單獨調用append將項目添加到年底for循環內。

place_holder = [ sweedish[item] for item in new if item in sweedish ] 

變量本身是不必要的,因爲你可以直接把列表解析在for循環:

for item in [ sweedish[item] for item in new if item in sweedish ]: 
+0

簡單,優雅,哦如此有效。謝謝一堆! – 2014-09-03 16:22:08

0

由於@chepner說,你可以用一個列表理解簡明地建立新的列表從英文翻譯成瑞典語的單詞。

要訪問字典,您可能需要使用swedish.get(word,'null_value_placeholder'),所以如果您的英語單詞不在字典中,則不會得到KeyError。

在我的例子中,'None'是沒有在字典中翻譯的英文單詞的佔位符。您可以使用「'作爲佔位符,承認字典中的空白僅提供近似翻譯。

swedish = {'merry': 'god', 'christmas': 'jul', 'and': 'och', 'happy':'nytt','year':'ar'} 
english ='merry christmas and happy new year' 

def translate(s): 
    words = s.split() 
    translation = [swedish.get(word, 'None') for word in words] 
    print ' '.join(translation) 

translate(english) 

>>> 
god jul och nytt None ar 

或者,您可以在列表理解中放置條件表達式,以便列表理解只嘗試翻譯出現在字典中的單詞。

def translate(s): 
    words = s.split() 
    translation = [swedish[word] for word in words if word in swedish.keys()] 
    print ' '.join(translation) 

translate(english) 

>>> 
god jul och nytt ar 

''.join(translation)函數會將您的單詞列表轉換爲由''分隔的字符串。

+0

我喜歡使用get和格式。謝謝你,使用''.join比以前複雜的for循環要容易得多。 – 2014-09-03 16:24:06