python - 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 语句永远不会被执行。有什么我想念的吗?
解决方案
推荐阅读
- python - int 插入 np.array 浮点数组变成一个带有一堆 0 和 e^02 的浮点数
- amazon-web-services - 无法使用 ESP32 HTTPS 从 AWS Lambda 服务获取数据
- java - 价值四舍五入
- python - 从圆圈中删除填充
- mysql - PythonAnywhere SQLite/SQLAlchemy 突然出现错误
- excel - 使用不显示零值的 VBA 创建新工作表
- r - 如何在闪亮模块中选择输入 R6 类的元素子集以对其执行操作
- python - Python SymPy solve 与 nonlinsolve
- javascript - 使用其他按钮向 div 添加 +1
- akka - 如果一个分片的 Actor A 询问另一个 Actor B 但 A 在 B 响应之前被重新定位,会发生什么?