根据另一个列表给定的顺序对字典列表进行排序

huangapple go评论51阅读模式
英文:

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 = [{&quot;a&quot;: 5}, {&quot;b&quot;: 5}, {&quot;j&quot;: {}}, {123: &quot;z&quot;}]
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: &quot;z&quot;}, {&quot;b&quot;: 5}, {&quot;j&quot;: {}}, {&quot;a&quot;: 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
----&gt; 1 sorted(zip(b, a))

TypeError: &#39;&lt;&#39; not supported between instances of &#39;dict&#39; and &#39;dict&#39;

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]

huangapple
  • 本文由 发表于 2023年2月8日 20:33:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定