根据python中的索引交换数组索引

我正在尝试建立循环排序,以便提前知道数字范围

def cyclic_sort(nums):
  # TODO: Write your code here
  i = 0

  while i < len(nums):
    while nums[i] - 1 != i:
        nums[i],nums[nums[i] - 1] = nums[nums[i] - 1],nums[i]
    i += 1

  return nums


print(cyclic_sort([2,1,3]))

但是代码只是挂起,但是当我重构到下面的代码时,就会运行

def cyclic_sort(nums):
  # TODO: Write your code here
  i = 0

  while i < len(nums):
    while nums[i] - 1 != i:
        other = nums[i] - 1
        nums[i],3]))

有人可以帮助我了解发生了什么事吗?

iCMS 回答:根据python中的索引交换数组索引

nums [i]首先被重新分配,因此当nums [nums [i]-1] = ...被求值时,它将采用nums [i]的新值,在这种情况下为1。 /> 因此,在您的示例中,您得到nums [0] = 1,然后得到nums [1-1] = 2。

您正在将当前元素的值设置为要交换的新值,然后将位于被交换元素的位置的元素设置为当前值。

您的代码等同于:

        x,y = nums[nums[i] - 1],nums[i]
        nums[i] = x                 #nums[i] is set to value of element you want to swap
        nums[nums[i] - 1] = y       #nums[(value at swapped element) - 1] = (current elements original value)

您也不需要while循环,它没有任何用处,因为您已经基于该值知道数字应该位于哪个位置,因此您只需要对每个位置检查一次即可。

交换分配顺序,因为nums [i]不会因更改nums [nums [i]-1]的值而受到影响。

def cyclic_sort(nums):
  # TODO: Write your code here
  i = 0

  while i < len(nums):
    if nums[i] - 1 != i:
        nums[nums[i] - 1],nums[i] = nums[i],nums[nums[i] - 1]
    i += 1

  return nums


print(cyclic_sort([2,1,3]))
本文链接:https://www.f2er.com/1904756.html

大家都在问