2015-05-11 37 views
1

我試圖在Python中編寫一個函數,它將重新排列指定項目,將其移動到新位置,其他項目將在關係中移動。創建一個函數,重新排列列表中的項目並移動其他項目(Python)

函數接受兩個參數:

old_index - 我們想要的項目要移動

比方說,我有這個列表索引 - 項目 NEW_INDEX的當前索引:

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

我決定在字母'b'之前移動字母'f'。這意味着old_index = 5new_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 

但是那並不是」工作得很好。如果可能的話,我想避免製作副本(我的應用程序中的列表可能非常大)。

回答

3

從舊索引彈出,插入所需索引。

>>> 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'] 
+0

傳遞最簡單的解決方案。謝謝Stefan。 – user3056783

+0

總是很高興知道那裏已經有了什麼。或者至少有一個很好的直覺,應該在那裏,然後尋找它:-)。順便說一句,我改變了變量名爲「mylist」。如果你把它稱爲'list',那麼你不能再訪問Python自己的'list',這可能會讓人感到困惑。所以不是一個好主意。 –

1
def shift_letters(list, old_index, new_index): 
    value = list.pop(old_index) 
    list.insert(new_index, value) 
1

所以也許:

ls.insert(new, ls.pop(old))

相關問題