如何编写一个函数来根据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
如何编写一个函数来根据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仅重新排列的数目尝试这样(简单的解决方案编辑):
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]
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)]
使用列表理解:
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
你不需要result_list = [0] * LEN(dict_index),你可以这样做: result_list = [] 然后: result_list [指数] = dict_value [信] – scripts
不在这里工作了: IndexError:列出分配索引超出范围。尝试'[] [2] ='一些价值' – BoppreH