def funny_phrases(list):
funny = []
for word1 in list:
if len(word1) >= 6:
funny.append(word1)
phrases = []
for word2 in funny:
if word2[-1:] is "y":
phrases.append(word2)
return phrases
print(funny_phrases(["absolutely", "fly", "sorry", "taxonomy", "eighty", "excellent"]))
print(funny_phrases(["terrible", "normally", "naughty", "party"]))
print(funny_phrases(["tour", "guy", "pizza"]))我有这些循环,我想知道是否有任何方法可以简化它。
发布于 2019-09-21 09:28:31
同时测试这两个条件,将其减少为一个循环:
def funny_phrases(lst):
funny = []
for word in lst:
if len(word) >= 6 and word.endswith('y'):
funny.append(word)
return funny然后可以将其转换为列表理解,留下:
def funny_phrases(lst):
return [word for word in lst if len(word) >= 6 and word.endswith('y')]请注意,除了循环改进之外,我还做了两个小更改:
lst,以避免list构造函数的名称遮蔽(这会阻止您在需要时使用它).endswith('y'),该方法更易于自我记录(并且不需要临时str,就像切片一样)。<代码>G211
发布于 2019-09-21 09:31:35
您没有使用嵌套循环,但可以使用filter
def funny_phrases(words):
funny = filter(lambda word: len(word) >= 6, words)
return list(filter(lambda word: word[-1:] is "y", funny))顺便说一句,正如您所看到的,我将参数list重命名为words,因为它覆盖了list()函数。尽量不要在你的列表中调用list,而是使用更多的解释性名称。
或者一行:
def funny_phrases(words):
return list(filter(lambda word: word[-1:] is "y", filter(lambda word: len(word) >= 6, words)))或者进行单次迭代:
def funny_phrases(words):
return list(filter(lambda word: len(word) >= 6 and word[-1:] is "y", words))或者,如果您更喜欢列表理解:
def funny_phrases(words):
return [word for word in words if len(word) >= 6 and word[-1:] is "y"]此外,还可以改进一些东西:
word[-1:] is "y"相反,这并不好:
word.endswith("y")这更冗长,也更容易理解。
所以你的期末考试应该是两者中的一个:
def funny_phrases(words):
return [word for word in words if len(word) >= 6 and word.endswith("y")]
def funny_phrases(words):
return list(filter(lambda word: len(word) >= 6 and word.endswith("y"), words))我会使用列表理解,因为在我看来它们更冗长,但这取决于你。
正如@ShadowRanger评论的那样,列表理解对于这项任务来说是一个相当好的选择。它们看起来更好,在这种情况下(使用lambda),它们比filter更快。
发布于 2019-09-21 11:01:59
def funny_phrases(list):
return [(l) for l in list if len(l)>6 and l[len(l)-1] == 'y']
print(funny_phrases(["absolutely", "fly", "sorry", "taxonomy", "eighty", "excellent"]))
['absolutely', 'taxonomy']https://stackoverflow.com/questions/58036588
复制相似问题