2012-11-22 48 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