2012-11-22 72 views

回答

1

以L僅重新排列的數目嘗試這樣(簡單的解決方案編輯):

L=[('b',3),('a',2),('c',1)] 

dict_index={'a':0,'b':1,'c':2} 

# Creates a new empty list with a "slot" for each letter. 
result_list = [0] * len(dict_index) 

for letter, value in L: 
    # Assigns the value on the correct slot based on the letter. 
    result_list[dict_index[letter]] = value 

print result_list # prints [2, 3, 1] 
+0

你不需要result_list = [0] * LEN(dict_index),你可以這樣做: result_list = [] 然後: result_list [指數] = dict_value [信] – scripts

+0

不在這裏工作了: IndexError:列出分配索引超出範圍。嘗試'[] [2] ='一些價值' – BoppreH

1

sorted和列表的.sort()方法採取key參數:

>>> L=[('b',3),('a',2),('c',1)] 
>>> dict_index={'a':0,'b':1,'c':2} 
>>> sorted(L, key=lambda x: dict_index[x[0]]) 
[('a', 2), ('b', 3), ('c', 1)] 

>>> [x[1] for x in sorted(L, key=lambda x: dict_index[x[0]])] 
[2, 3, 1] 

應該這樣做。對於更有趣的例子 - 你恰好與數字順序匹配字母順序,因此很難看到它真正的工作 - 我們可以洗牌dict_index一點:

>>> dict_index={'a':0,'b':2,'c':1} 
>>> sorted(L, key=lambda x: dict_index[x[0]]) 
[('a', 2), ('c', 1), ('b', 3)] 
1

使用列表理解:

def index_sort(L, dict_index): 
    res = [(dict_index[i], j) for (i, j) in L]  #Substitute in the index 
    res = sorted(res, key=lambda entry: entry[0]) #Sort by index 
    res = [j for (i, j) in res]     #Just take the value 

    return res