【问题标题】:How to expand a list comprehension with two foor loops in Python?如何在 Python 中使用两个 for 循环扩展列表理解?
【发布时间】:2021-08-17 05:37:32
【问题描述】:

给定以下来自 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)

有什么想法吗?

【问题讨论】:

  • 要记住的一件事:在循环内操作被循环的任何内容都不是一个好主意。在 for 循环情况下,combs 在循环时被扩展。如果您仔细观察,列表理解示例中不会发生这种情况。

标签: python list for-loop list-comprehension


【解决方案1】:

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

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 中所示的简单操作。

【讨论】:

  • 我明白了,这更有意义!显然,我对列出基础知识之外的理解相对较新,但这可以解决问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多