<p>切换列表中的元素实际上非常简单:</p>
<pre><code>myList[0], myList[1] = myList[1], myList[0]
</code></pre>
<p>这将交换<code>myList</code>中的第一个和第二个元素。Python实际上有一个优化的字节码命令,它可以非常快速地交换程序堆栈上的两个值,所以这与交换列表值的速度差不多。你知道吗</p>
<p>当然,在这种情况下,您不会返回新列表,而是修改旧列表。因此,您只需编写<code>switch(myList, 2)</code>,而不是<code>myList = switch(myList, 2)</code>。代码如下所示:</p>
<pre><code>def switch(lst, i):
lst[0], lst[i] = lst[i], lst[0]
</code></pre>
<p>如果要返回一个全新的列表,需要先复制一份:</p>
<pre><code>def switch(lst, i):
newlst = list(lst)
newlst[0], newlst[i] = newlst[i], newlst[0]
return newlst
</code></pre>
<p>编辑:如果你使用的是链表,那就有点不同了。我认为链表不存在Python优化;常规列表非常容易添加项,并且它们可以处理任何类型的对象,因此链表在Python中非常失去其用途。不过,这里有一个建议:</p>
<pre><code>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
</code></pre>
<p>链表操作就是要维护到下一个项目的正确链接。另外请注意,如果您试图交换一个链接列表中实际上不存在的位置,则上述代码将失败。检查你的输入。你知道吗</p>