英文:
Sort list of dictionaries based on the order given by another list
问题
有很多类似的问题在Stack Overflow上,但并非完全相同。
我需要根据另一个列表的值对字典列表进行排序,但(与我找到的所有其他问题不同)第二个列表只是提供顺序,并不是字典的元素。
假设我有这些列表
a = [{"a": 5}, {"b": 5}, {"j": {}}, {123: "z"}]
b = [8, 4, 4, 3]
其中 b
不包含列表中字典的值,但提供(升序)用于对 a
进行排序的顺序,因此我希望输出为:
[{123: "z"}, {"b": 5}, {"j": {}}, {"a": 5}]
我尝试过 sorted(zip(b, a))
但是会出错,可能是因为当它找到平局时,它试图在第二个列表上进行排序。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[497], line 1
----> 1 sorted(zip(b, a))
TypeError: '<' not supported between instances of 'dict' and 'dict'
在出现平局的情况下,保留原始顺序是可以的。
英文:
There are a lot of similar questions on Stack Overflow but not exactly this one.
I need to sort a list of dictionaries based on the values of another list but (unlike all the other questions I found) the second list just gives the order, is not an element of the dictionary.
Let's say I have these lists
a = [{"a": 5}, {"b": 5}, {"j": {}}, {123: "z"}]
b = [8, 4, 4, 3]
Where b
does not contain values of the dictionaries in the list, but gives the order (ascending) to use to sort a
, therefore I want the output to be:
[{123: "z"}, {"b": 5}, {"j": {}}, {"a": 5}]
I tried sorted(zip(b, a)
but this gives an error probably because when it finds a tie it tries to sort on the second list
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[497], line 1
----> 1 sorted(zip(b, a))
TypeError: '<' not supported between instances of 'dict' and 'dict'
In case of ties it's fine to leave the original order
答案1
得分: 2
你可以对第二个列表进行排序,然后根据结果对第一个列表进行排序
sort_b_indexes = sorted(range(len(b)), key=lambda x: b[x])
a = [a[i] for i in sort_b_indexes]
英文:
You can sort the second list, and then sort the first list based on the result
sort_b_indexes = sorted(range(len(b)),key=lambda x:b[x])
a = [a[i] for i in sort_b_indexes]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论