我知道这个问题已经被问过很多次了。当我搜索时,我通常会得到与交换列表中的元素有关的答案。
我不希望交换列表中的元素,而是将元素从一个位置移动到另一个位置。
示例(移动元素 0:
[1,2,3,4,5]
输出:
[2,3,1,4,5]
示例(移动元件 2):
[1,2,3,4,5]
输出:
[1,2,4,5,3]
是否有一个内置的 python 函数可以让我这样做?
PS我不是要你们教我怎么做……我是问python中是否有inbult函数!!!!!!!!!
沿着这条线的东西可能:
def move (iter, from_, to):
iter.insert (to, iter.pop (from_) )
根据您的问题,尚不清楚您正在寻找的确切功能是什么,因此这里有一些功能应该可以实现您正在寻找的任何转换。
这是一个函数,可以将列表中位置 x 的值交换为位置 y 的值,反之亦然。
def swap(mylist, x, y):
"""Swaps position x for position y in a list"""
swap1 = mylist[x]
swap2 = mylist[y]
mylist[y] = swap1
mylist[x] = swap2
return mylist
这是一个将位置 x, y 位置的值向前移动的函数。
def moveforward(mylist, x, y):
""""Function moves the value at position x, y positions forward, keeping x in its original position"""
move1 = mylist[x]
mylist[x + y] = move1
return mylist
这是一个将每个值从 x 向前旋转一个值的函数,将列表末尾的值移动到 x。
def rotate(mylist, x):
"""Rotates all values from x onwards one value forward, moving the end of the list to x."""
replace = x + 1
while replace < len(mylist):
mylist[replace] = mylist[replace - 1]
replace += 1
mylist[x] = mylist[replace - 1]
return mylist
最后:
def rotateback(mylist, x, y):
"""Rotates every value beyond x one back and places value mylist[x] at position mylist[y]""".
xx = mylist[x]
while x < y:
mylist[x] = mylist[x + 1]
x += 1
mylist[y] = xx
return mylist