Python 如何简化这些循环?

Python 如何简化这些循环?,python,python-3.x,Python,Python 3.x,我有这些循环,想知道是否有任何方法可以简化它。立即测试两个条件,将其减少为一个循环: 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":

我有这些循环,想知道是否有任何方法可以简化它。

立即测试两个条件,将其减少为一个循环:

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"]))
然后可以将其转换为列表理解,留下:

def funny_phrases(lst):
    funny = []
    for word in lst:
        if len(word) >= 6 and word.endswith('y'):
            funny.append(word)
    return funny
请注意,除了循环改进之外,我还做了两个小改动:

  • 我将变量名更改为
    lst
    ,以避免名称对
    列表
    构造函数造成阴影(如果您需要的话,这会阻止您使用它)
  • 我将带幻数的切片更改为命名方法
    .endswith('y')
    ,它更能自我记录(并且不像切片那样需要临时
    str
    s)

  • 您没有使用嵌套循环,但可以使用:

    顺便说一下,正如您所见,我将您的参数
    list
    重命名为
    words
    ,因为它覆盖了函数。尽量不要在列表中调用
    list
    ,而是使用更多的解释性名称

    或者在一行中:

    def funny_phrases(words):
        funny = filter(lambda word: len(word) >= 6, words)
        return list(filter(lambda word: word[-1:] is "y", funny))
    
    或者进行一次迭代:

    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")
    
    我会使用列表理解,因为在我看来它们更详细,但这取决于你

    如前所述,对于这项任务,列表理解是一个更好的选择。它们看起来更好,在这种情况下(使用lambda),它们比
    filter

    def搞笑短语(列表)更快:
    如果len(l)>6且l[len(l)-1]='y',则为列表中的l返回[(l)]
    打印(有趣的短语([“绝对”,“飞行”,“抱歉”,“分类”,“八十”,“优秀]))
    [“绝对”、“分类法”]
    
    这不是嵌套循环。这是两个循环,两个循环都没有嵌套在另一个循环中。@ShadowRanger我编辑了标题和正文来解决这个问题。谢谢。注意:
    map
    /
    filter
    只是在转换/谓词函数是用C实现的内置函数时,相对于等价的列表理解或生成器表达式的一个改进。如果
    map
    /
    filter
    需要listcomp/genexpr可以避免的
    lambda
    ,它们总是比较慢,而且通常更难看,正如你在回答中比较这两个问题时所看到的那样。@ShadowRanger,这就是为什么我总是喜欢列表理解:)!此外,要明确的是,列表理解是一种函数式编程结构<代码>映射/
    过滤器
    的功能既没有增加也没有减少;它们都是函数式编程工具。如果人们声称更喜欢
    filter
    ,因为它更“实用”,他们不知道自己在说什么。@ShadowRanger,关于这一部分,我不能说什么,因为我不知道函数式编程,我只是在重复一些(错误的)人告诉我的。
    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))