有没有办法在 Python 中多行编写 for 循环? [复制]

社会演员多 python 401

原文标题Is there any way to write a for loop in multiple lines in Python? [duplicate]

这个问题在这里已经有了答案:“列表理解”和类似的意思是什么?它是如何工作的,我该如何使用它? (5 个答案) 57 分钟前关闭。

我正在查看具有以下功能的代码。我想知道是否可以在多行中编写 for 循环并返回与以下相同的确切值。

def RecordsLists(self, a, q):
   return set([a1.union(a2) for a1 in a for a2 in a if len(a1.union(a2)) == q])

原文链接:https://stackoverflow.com//questions/71685994/is-there-any-way-to-write-a-for-loop-in-multiple-lines-in-python

回复

我来回复
  • Lei Yang的头像
    Lei Yang 评论

    为什么不?所有列表推导都等于循环。

    def RecordsLists(self, terms, q):
        lst = []
        for term1 in terms:
            for term2 in terms:
                unioned = term1.union(term2)
                if len(unioned) == q:
                    lst.append(unioned)
        return set(lst)
    

    唯一关心的是两个循环的顺序,但我认为它不会影响这个算法的结果。

    1年前 0条评论
  • BrokenBenchmark的头像
    BrokenBenchmark 评论

    是的,你可以使用itertools.product()。嵌套for循环是可以的,但在我看来,它们增加了不必要的缩进量。

    from itertools import product
    def RecordsLists(self, a, q):
        result = []
        for a1, a2 in product(a, repeat=2):
            union = a1.union(a2)
            if len(union) == q:
                result.append(union)
        return set(union)
    
    1年前 0条评论