Python 如何编写函数根据索引字典重新排列列表
如何编写函数根据python中的索引字典重新排列列表 比如说,Python 如何编写函数根据索引字典重新排列列表,python,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_索引仅重新排列L中的数字(使用更简单的解决方案编辑): sorted和列表的.sort()方法采用键参数: >>> L=[('b',3),('a',2),('c',1)] &g
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_索引仅重新排列L中的数字(使用更简单的解决方案编辑):
sorted
和列表的.sort()
方法采用键
参数:
>>> 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\u 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\u list=[0]*len(dict\u index),只需执行以下操作:result\u list=[],然后:result\u list[index]=dict\u值[letter]在这里不起作用:
索引器:列表分配索引超出范围
。请尝试[[2]=“一些值”
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