如何使用python将这个函数/for循环转换成一个列表理解函数或更高阶的函数?

2024-09-30 01:31:51 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,我用函数和for循环编写了以下简单的翻译程序,但我试图更好地理解列表理解/高阶函数。我对map和listEncomprehension之类的函数有非常基本的了解,但是当循环需要占位符值(如下面代码中的place\u holder)时,我不知道如何使用它们。此外,任何关于我可以做得更好的建议将不胜感激。提前谢谢,你们太棒了!你知道吗

另外,在我发布的代码看起来像记事本++的地方,你是如何得到这种奇特的格式的?你知道吗

    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] ))

Tags: andthe函数innewforenglishplace
2条回答

正如@chepner所说,您可以使用列表理解来简明地构建从英语翻译成瑞典语的新单词列表。你知道吗

要访问词典,您可能需要使用瑞典语。明白吗(单词'null\u value\u placeholder'),因此如果您的英语单词不在词典中,则不会出现键错误。你知道吗

在我的例子中,“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)函数将把单词列表转换为以“”分隔的字符串。你知道吗

列表理解只是一次构建一个列表,而不是单独调用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 ]:

相关问题 更多 >

    热门问题