如何在列表的索引处与列表头部交换节点?

2024-06-16 09:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试创建一个函数,该函数将在索引处用列表头切换节点。因此,如果我的list(list)有值[1, 7, 9, 12],我调用switch(list, 2),我的结果将是[9, 7, 1, 12]。这是我目前掌握的代码:

def switch(list, index):
    ....

def testSwitch():
#test code to ensure that switch() is working correctly.
myList = createList([10, 20, 30, 40, 50, 60])
print "The initial list", listString(myList)
myList = switch(myList, 2)
print "Switching the head and the 30.  Resulting list is ", listString(myList)
myList = switch(myList, 5)
print "Switching the head and the 60.  Resuling list is ", listString(myList)
myList = switch(myList, 29)  #should result in an error

Tags: andthe函数列表节点isdefhead
2条回答

切换列表中的元素实际上非常简单:

myList[0], myList[1] = myList[1], myList[0]

这将交换myList中的第一个和第二个元素。Python实际上有一个优化的字节码命令,它可以非常快速地交换程序堆栈上的两个值,所以这与交换列表值的速度差不多。你知道吗

当然,在这种情况下,您不会返回新列表,而是修改旧列表。因此,您只需编写switch(myList, 2),而不是myList = switch(myList, 2)。代码如下所示:

def switch(lst, i):
  lst[0], lst[i] = lst[i], lst[0]

如果要返回一个全新的列表,需要先复制一份:

def switch(lst, i):
  newlst = list(lst)
  newlst[0], newlst[i] = newlst[i], newlst[0]
  return newlst

编辑:如果你使用的是链表,那就有点不同了。我认为链表不存在Python优化;常规列表非常容易添加项,并且它们可以处理任何类型的对象,因此链表在Python中非常失去其用途。不过,这里有一个建议:

def switch(ll, i):
  head = ll
  currentItem = ll      # The head again
  prevItem = None       # The item that links to tempItem
  for x in range(i):    # Find the item to swap
    prevItem = currentItem
    currentItem = currentItem.next

  # Now we swap. We're rotating three items' .next values, so we can't
  # do the really optimized way.
  temp = currentItem.next
  currentItem.next = head.next
  head.next = prevItem.next
  prevItem.next = temp

链表操作就是要维护到下一个项目的正确链接。另外请注意,如果您试图交换一个链接列表中实际上不存在的位置,则上述代码将失败。检查你的输入。你知道吗

您可以用切换两个变量的相同方法来执行此操作:

def switch(x, ix):
    # x = x[:]
    x[0], x[ix] = x[ix], x[0]
    # return x

这将修改现有列表。如果要返回新列表,请取消注释注释行。你知道吗

相关问题 更多 >