首页 > 解决方案 > Python - 没有追加时追加列表?

问题描述

我正在尝试解决 python 中的编码挑战,但值似乎在没有我附加它们的情况下发生变化。

预期行为:

输入:nums = [1,2,2]

输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
    possibleSets = [[]]
    for i in range(len(nums)):
        newSet = []
        newSet.append(nums[i])
        if newSet not in possibleSets:
                possibleSets.append(newSet)
                print('possibleSets 1====>', possibleSets)
        for j in range(len(nums)-1):
            newSet.append(nums[j+1])
            print('newSet====>', newSet)
            print('possibleSets 2====>', possibleSets)
            if newSet not in possibleSets:
                possibleSets.append(newSet)
    return possibleSets  

印刷:

possibleSets 1====> [[], [1]]
newSet====> [1, 2]
possibleSets 2====> [[], [1, 2]]
newSet====> [1, 2, 2]
possibleSets 2====> [[], [1, 2, 2]]
possibleSets 1====> [[], [1, 2, 2], [2]]
newSet====> [2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2]]
newSet====> [2, 2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2, 2]]
possibleSets 1====> [[], [1, 2, 2], [2, 2, 2], [2]]
newSet====> [2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2, 2], [2, 2]]
newSet====> [2, 2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2, 2], [2, 2, 2]]

不知何故,在第一次和第二次打印之间,“possibleSets”的值正在改变,打印 1 之前的附加值被覆盖newSet.append(nums[j+1])。这会导致最终的 if 语句永远不会被执行。有什么我想念的吗?

标签: pythonpython-3.x

解决方案


推荐阅读