大家好,我用一個函數和循環編寫了下面這個簡單的翻譯程序,但是我試圖更好地理解列表理解/高階函數。我對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]))
精美的代碼突出顯示已經存在於您的問題中,但正確的語法是縮進4個空格的任何文本塊將被視爲代碼塊,渲染時會觸發語法高亮顯示器。 – rennat 2014-09-03 16:04:33
我現在看到它,它沒有出現之前.. – 2014-09-03 16:24:25