Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于其他数组对python中dict的数组进行排序_Python_Sorting - Fatal编程技术网

基于其他数组对python中dict的数组进行排序

基于其他数组对python中dict的数组进行排序,python,sorting,Python,Sorting,我有一个dict数组,[{'id':1,'name':'one'},{'id':2,'name':'two'},{'id':3,'name':'three'}]和带有排序id的数组[3,1,2] 预期的结果是 [{'id':3,'name':'three'},{'id':1,'name':'one'},{'id':2,'name':'two'}] 最好的方法是什么 我的代码基于以下两个方面: a = [{'id': 1, 'name': 'one'}, {'id': 2, 'name': 'tw

我有一个dict数组,
[{'id':1,'name':'one'},{'id':2,'name':'two'},{'id':3,'name':'three'}]
和带有排序id的数组
[3,1,2]

预期的结果是

[{'id':3,'name':'three'},{'id':1,'name':'one'},{'id':2,'name':'two'}]

最好的方法是什么

我的代码基于以下两个方面:

a = [{'id': 1, 'name': 'one'}, {'id': 2, 'name': 'two'}, {'id': 3, 'name': 'three'}]
b = [3, 1, 2]

res = []

for index in b:
    for player in a:
        if index == player['id']:
            res.append(player)

print(res)
试试这个:

>>> a = [{'id': 1, 'name': 'one'}, {'id':2, 'name': 'two'}, {'id': 3, 'name': 'three'}]
>>> b = [3,1,2]
>>> sorted(a, key= lambda x: l.index(x['id']))
[{'id': 3, 'name': 'three'}, {'id': 1, 'name': 'one'}, {'id': 2, 'name': 'two'}]
>>> a = [{'id': 1, 'name': 'one'}, {'id':2, 'name': 'two'}, {'id': 3, 'name': 'three'}]
>>> b = [3,1,2]
>>> sorted(a, key= lambda x: l.index(x['id']))
[{'id': 3, 'name': 'three'}, {'id': 1, 'name': 'one'}, {'id': 2, 'name': 'two'}]