使用嵌套列表索引时,Pythonic 交换导致索引错误

Pythonic swap result in index error when using nested list index

我知道 pythonic swap 可以写成:

a,b = b,a
list[a], list[b] = list[b], list[a]

但是在我的问题中,我想交换列表中的元素,但是我使用的索引是原始列表中某个索引位置的值。它是这样工作的:

假设我有一个要交换的列表 nums,并且我有一个索引 i。

nums = [-10,-3,-100,-1000,-239,1]  # list to swap
i = 5  # index

这里我们可以假设

if nums[i] > 0 and nums[i]<=len(nums)

交换后我期望的是:

[1, -3, -100, -1000, -239, -10]

以下命令给我索引超出范围错误:

nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]   # gives list assignment out of range error

而以下命令工作正常:

t = nums[i]
nums[i] = nums[t-1]
nums[t-1] = t

我很困惑,请告诉我我哪里错了。

这是因为交换两个变量在 Python 中的工作方式。

请注意,即使您得到 AssignmentError,如果您之后打印出您的列表,您也会得到

>>> nums
[-10, -3, -100, -1000, -239, -10]

这是因为在

右侧创建的元组
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]

被解包并分配给左侧,在解包期间评估左侧。

所以

  • 创建了 RHS 元组,值为 (-10, 1)
  • nums[i] 被分配为 -10
  • 然后您尝试将 nums[nums[i]-1] 分配为 1... 但是由于 nums[i] 在这一点 被评估 并且是现在-10,您的索引现在将是-11,给出错误。