Python中嵌套在列表中的元组的任意顺序
我有一个从 Solr 返回的元组列表,如下所示:
[('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)]
请注意,不仅返回了第二个、第三个、第九个和第十一个电路。
我需要根据我的排序元组对其进行排序:
COURT_ORDER = (
'Supreme Court',
'First Circuit',
'Second Circuit',
'Third Circuit',
'Fourth Circuit',
...and so on...,
)
排序后所需的输出将是:
[('Second Circuit', 34), ('Third Circuit', 4), ('Ninth Circuit', 24), ('Eleventh Circuit', 2)]
是否有一种聪明的方法可以做到这一点?
(如果可能的话,这需要标记为“晒伤”标签,但由于缺乏积分,我无法创建它。)
I have a list of tuples like the following that I'm getting back from Solr:
[('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)]
Note that not only the second, third, ninth and eleventh circuits were returned.
I need to order this according to an ordering tuple I have that looks like this:
COURT_ORDER = (
'Supreme Court',
'First Circuit',
'Second Circuit',
'Third Circuit',
'Fourth Circuit',
...and so on...,
)
The desired output, after sorting would be:
[('Second Circuit', 34), ('Third Circuit', 4), ('Ninth Circuit', 24), ('Eleventh Circuit', 2)]
Is there a clever way of doing this?
(This needs to get tagged with the Sunburnt tag, if possible, but I can't create it, for lack of points.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建立一个字典,将法院名称映射到所需的排名。然后使用 关键函数 进行排序,该函数查找法院名称以找到排名:
有关如何排序的更多见解,请参阅排序 HOWTO。
Build a dictionary that maps the court name to the desired ranking. Then sort with a key function that looks up the court name to find the ranking:
For more insights on how to sort, see the Sorting HOWTO.
根据
[0]
项目在COURT_ORDER
中首次出现的索引
来key
项目:key
the items according to theindex
of the first appearance of their[0]
item in theCOURT_ORDER
: