python - 有没有办法让函数的输出将字符串转换为与输入相同的顺序?
问题描述
对不起,如果标题令人困惑。我正在做的练习是编写一个带有两个参数的函数:一个将瑞典语单词映射到英语的字典,以及一个对应于瑞典语句子的字符串。该函数应将句子的翻译返回为英文
我的函数在翻译方面运行良好,但它产生的输出顺序错误。
例如,以下参数,由一个字典和一个瑞典语字符串组成(英语:“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字典没有排序,有没有办法让输出与句子的顺序相同?
解决方案
这种单线似乎工作正常。在字典中查找每个单词并按照与输入句子相同的顺序加入。
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'
>>>
推荐阅读
- javascript - 通过键将数组列表的元素分组/连接在一起
- html - 无法在较新的詹金斯版本中使用页面标记插件
- python-3.x - selenium.common.exceptions.NoSuchElementException:消息:Python selenium 中没有此类元素错误,即使 HTML 中存在 ID 和名称
- c# - ASP .NET Core - 如何判断数据协定属性是否未设置或设置为 null
- java - 我的 ArrayList 两次打印同一个对象
- r - 是否可以在 R 中为时间序列设计执行多维分段泊松回归?
- android - 在运行时更改 BottomNavigationView 的图标
- javascript - React.js:元素类型无效:
- c - “void”是标量类型吗?
- java - 在 Android 中切换案例以将图像替换为另一个图像。像 Tinder Image 交换器之类的东西