压缩if循环python

压缩if循环python,python,list-comprehension,Python,List Comprehension,我想用Python中的def返回这些结果: title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings' title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows' title_case('the quick brown fox') # should return: 'The

我想用Python中的def返回这些结果:

title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
title_case('the quick brown fox') # should return: 'The Quick Brown Fox'
解决方案可以是:

def title_case(title, minor_words=''):
    title = title.capitalize().split()
    minor_words = minor_words.lower().split()
    return ' '.join([word if word in minor_words else word.capitalize() for word in title])
我听不懂最后一行。我从中得到的是: 如果'word'在'minor_words'中,则加入'minor_words'==>这不是我们想要的。我们想加入“头衔”

第二个问题是关于这个解决方案的第一行。为什么会有=? 我试着写下带和不带这个的小单词,结果是一样的

如果'word'在'minor_words'中,加入'minor_words'

不,不是这个意思

小调单词中的单词if-word意味着,若单词在小调单词中,我们连接单词,这是一个来自标题的单词

else word.capitalize意味着如果单词不在小词中,我们就加入大写的单词

为什么会有=

它为minor_words参数提供默认值。在上一个示例中,您仅使用一个参数调用函数:

title_case('the quick brown fox')
这相当于:

title_case('the quick brown fox', '')

如果没有默认值,则会出现一个错误,即没有提供足够的参数。

minor\u words=是默认值。如果只使用一个参数调用函数,则第二个参数默认为空字符串。如果省略=第三个示例将出现错误。传递标题并让函数将其拆分为单词是一回事;次要词语应该是一个列表,以其开头。@Barmar因此,在插入任何内容之前,此默认值在次要词语中插入一个“”,如果没有任何内容作为次要词语,则不会出现错误。我说得对吗?没错。