列表理解的扩展导致列表幂集中的无限循环

Expansion of list comprehension leading to infinite loop in listing power sets

我一直在尝试解决在 Question 78 on Leetcode. I ran into a solution that uses list comprehensions and it works. I tried expanding it and following through with the Python documentation 上列出幂集的问题,以确保我得到正确的语法,但我似乎陷入了无限循环。

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解决方案中的代码是:

    def subsets(nums):
        nums.sort()
        result = [[]]
        for num in nums:
            result += [i + [num] for i in result]
        return result 

我修改后的代码是:

  def subsets(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    result = [[]]

    for num in nums:
      for list_ in result:
        result.append([num] + list_)
    return result

我认为在 for list_ in result: 循环的每次迭代中,结果会越来越大,所以我不会结束它,但为什么它与列表理解的情况不同?我错过了什么?

因为首先 [i + [num] for i in result] 被解析,然后一旦计算出来,就会发生 result += 部分,这与你的 1 乘 1 追加不同。另一个解决方案是一次追加所有所以没有问题