2014-01-17 37 views
0

我有這樣的功能:怎麼辦元素的穩定就地相對重新排序列表中的

def relative_reorder(my_list, before, after): 
    backup_of_my_list = list(my_list) 
    def my_key(item): 
     if item is after: 
      return backup_of_my_list.index(before) * 2 + 1 
     else: 
      return backup_of_my_list.index(item) * 2 
    my_list.sort(key=my_key) 

這可以這樣使用:

stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
relative_reorder(stack, 9, 7) 
print(stack) 
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 9, 9, 8, 8] 

但我想希望改善排序穩定性

我會考慮輸出,如這些優選的:

[1, 2, 3, 4, 5, 6, 8, 9, 1, 2, 3, 4, 5, 6, 8, 9, 7 ,7] 
[1, 2, 3, 4, 5, 6, 9, 9, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] 

目標是對列表重新排序,以便所有出現的9的索引都低於所有出現的7,同時儘可能地保持列表中的穩定性。一個使用這可能是命令可能需要運行某些任務,而我們知道,某個任務前應另一項任務始終運行...

+0

這些結果似乎並不一致......你究竟在做什麼...第一個看起來就像你只是將某個值移動到最後......我不確定實際的排序是什麼發生在這裏... –

+0

@JonClements我修改了這個問題,希望我的目標更清晰了 –

回答

0
def last_index(l, value): 
    """ 
    Find the last occurance of value in the list 
    """ 
    # http://stackoverflow.com/q/522372/693869#comment336488_522401 
    return len(l) - 1 - l[::-1].index(value) 

def move_item(l, old, new): 
    """ 
    Move an item from an old index to a new index 
    """ 
    l.insert(new, l.pop(old)) 

def relative_reorder(l, before, after): 
    """ 
    reorder list so that all occurrences of before are of a lower 
    index than all occurrences of after 
    """ 
    while last_index(l, before) > l.index(after): 
     move_item(l, last_index(l, before), l.index(after)) 

stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
relative_reorder(stack, 9, 7) 
print(stack) 
[1, 2, 3, 4, 5, 6, 9, 9, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] 

如果任何人有一個更清楚地版本,生病接受