Skip to main content
 首页 » 编程设计

python之创建一个重新排列列表中的项目并移动其他项目的函数 (Python)

2025年05月04日53zlslch

我正在尝试用 Python 编写一个函数来重新排列指定的项目,将其移动到新的位置,其他项目将相应地移动。

该函数接受两个参数:

old_index - 项目的当前索引 new_index - 我们希望将项目移动到的索引

假设我有这个列表:

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

我决定将字母“f”移到字母“b”之前。这意味着 old_index = 5 和 new_index = 1。完成此操作后,我希望将字母移动而不是交换,结果如下:

list = ['a', 'f', 'b', 'c', 'd', 'e', 'g']

我想出了以下功能:

def shift_letters(old_index, new_index): 
 
    shifted = list.index(list[old_index]) 
    selected = list[old_index] 
    print 'selected', selected 
    list.insert(new_index, selected) 
    print 'inserted %s at %s' % (selected, new_index) 
    if old_index < new_index: 
        removed = list.pop(shifted - 1) 
    else: 
        removed = list.pop(shifted + 1) 
 
    print 'removed %s' % removed 

但这并不是很好。如果可能,我想避免制作列表的副本(我的应用程序中的列表可能非常大)。

请您参考如下方法:

从旧索引中弹出,插入到想要的索引处。

>>> mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
>>> old_index = 5 
>>> new_index = 1 
>>>  
>>> mylist.insert(new_index, mylist.pop(old_index)) 
>>> mylist 
['a', 'f', 'b', 'c', 'd', 'e', 'g']