如何编写一个函数来根据索引字典重新排列列表

时间:2012-11-22 03:14:00

标签: python

如何编写一个函数来根据python中的索引字典重新排列列表?

例如,

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

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

我想要一份清单:

   [2,3,1]

其中2来自'a',3来自'b',1来自'c',但根据dict_index重新排列L中的数字

3 个答案:

答案 0 :(得分:1)

试试这个(用更简单的解决方案编辑):

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]

答案 1 :(得分: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)]

答案 2 :(得分: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