首页 > 解决方案 > 有没有办法让函数的输出将字符串转换为与输入相同的顺序?

问题描述

对不起,如果标题令人困惑。我正在做的练习是编写一个带有两个参数的函数:一个将瑞典语单词映射到英语的字典,以及一个对应于瑞典语句子的字符串。该函数应将句子的翻译返回为英文

我的函数在翻译方面运行良好,但它产生的输出顺序错误。

例如,以下参数,由一个字典和一个瑞典语字符串组成(英语:“A fine monkey”)

translate_sentence({'en': 'a', 'fin': 'fine', 'apa': 'monkey'}, 'en fin apa')  

应该返回

'a fine monkey'

但相反它返回

'a monkey fine'

这是该函数的脚本:


def translate_sentence(d, sentence): 
    result = []                     
    delimiter = ' '                 
    s = sentence.split()            
    for word in d:                        
        if word in sentence and word in d:
            d_word = (d[word])
            result.append(d_word)
    for word in s:                          
        if word in s and word not in d:
            s_word = word
            result.append(s_word)
    return delimiter.join(result)    

正如我之前所说,问题在于该函数返回了带有错误顺序的单词的翻译字符串。我知道python字典没有排序,有没有办法让输出与句子的顺序相同?

标签: pythonlistdictionary

解决方案


这种单线似乎工作正常。在字典中查找每个单词并按照与输入句子相同的顺序加入。

def translate_sentence(d, sentence): 
    return ' '.join(d.get(word, word) for word in sentence.split())

例子:

>>> translate_sentence({'en': 'a', 'fin': 'fine', 'apa': 'monkey'}, 'en fin apa')  
'a fine monkey'
>>> 

推荐阅读