python - 在压缩和枚举期间修改 python 列表
问题描述
我有一个简单的算法,可以计算一个列表是否可以通过 1 个或更少的数字修改来实现非递减。我不确定(或询问)它是否有效,这是关于 python 语义的。我将我的 2 个问题总结为评论:
def checkPossibility(self, nums: List[int]) -> bool:
decrease_found = False
for (i,val1),(j, val2) in zip(enumerate(nums[::1]), enumerate(nums[1::1])):
# !!!! Why do i and j have the same values? They start at different indices
print('%d,%d - %d,%d' % (i, val1, j, val2))
if val1 > val2:
if decrease_found:
return False
else:
decrease_found = True
# !!!! This update is not being represented on the next iteration (i -> i + 1)
# i.e. val1 is not being updated in the subsequent print statement
nums[i + 1] = nums[i]
print("new nums is " + str(nums[i + 1]))
print(nums)
return True
输入:
[3,4,2,3]
输出:
0,3 - 0,4
[3, 4, 2, 3]
1,4 - 1,2
new nums is 4
[3, 4, 4, 3]
2,2 - 2,3
[3, 4, 4, 3]
我不明白为什么在我的输出中 i == j。我也不明白为什么我的 nums[i + 1] 没有更新后续迭代的 val1 值,因为 nums[i + 1] 指向它。
最好的猜测是 zip(enumerate... 正在复制两个列表并对其进行迭代,这将使 j 准确并通过 nums 数组修改改变 val1/val2 是不可能的。虽然我找不到这种行为的根源。
解决方案
推荐阅读
- mysql - Mysql查询根据另一个表的ID替换名称
- php - Laravel 模型绑定多对多关系不会填充数据
- python - 当我尝试打印时,行继续字符错误后出现意外字符
- mongodb - Mongodb - 从字段数组创建值的排名
- ios - 在 iOS 中检查设备屏幕打开或关闭
- json - 如果使用 Slurper 通过字符串传递 Xpath,如何从 JSON 获取数组值
- python - Python/Tkinter OptionMenu Update 创建菜单的“阴影”
- django - 外循环值与内循环值不匹配:Django 模板
- cmake - CMake WORLD_WRITE 权限不适用于 INSTALL
- postgresql - 估计 PostgreSQL 中删除列的影响大小