首页 > 解决方案 > 在压缩和枚举期间修改 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 是不可能的。虽然我找不到这种行为的根源。

标签: python

解决方案


推荐阅读