如何在 Python 中用两个 for 循环扩展列表理解?

How to expand a list comprehension with two foor loops in Python?

给定 Leetcode 中的以下代码:

def combine(self, n: int, k: int) -> List[List[int]]:
    combs = [[]]
    for _ in range(k):
        combs = [[i] + c for c in combs for i in range(1, c[0] if c else n+1)]
    return combs

如何扩展内部 combs 循环以提高可读性?我在下面进行了尝试,但是我遇到了关于 c[0] 部分的索引越界的错误,所以我知道我做错了什么,但是我在类似的列表理解中找不到一个非常相似的问题以了解我实际上做错了什么。

for c in combs:
            if c:
                for i in range(1, c[0]):
                    combs.extend([i] + c)
            else:
                for i in range(1, n+1):
                    combs.extend([i] + c)

有什么想法吗?

一旦您习惯了列表推导式,它本身就非常易读。例如,我更喜欢它,但至少会在那里添加一个换行符。以及“+”周围的一致空格。

def combine(self, n: int, k: int) -> List[List[int]]:
  combs = [[]]
  for _ in range(k):
    combs = [[i] + c for c in combs 
             for i in range(1, c[0] if c else n + 1)]
  return combs

为了帮助更好地理解它,这等同于 for 循环,我想您正在寻找:

def combine2(n: int, k: int):
    combs = [[]]
    for _ in range(k):
        tmp_combs = []
        for c in combs:
            for i in range(1, c[0] if c else n + 1):
                tmp_combs.append([i] + c)

        combs = tmp_combs
    return combs

此外,虽然这两个函数的结果相同,但它们在性能上存在一些差异。列表理解要快一些,尤其是对于 post.

中所示的简单操作