Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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中嵌套在列表中的元组的任意排序_Python_Sorting_Solr_Faceted Search - Fatal编程技术网

Python中嵌套在列表中的元组的任意排序

Python中嵌套在列表中的元组的任意排序,python,sorting,solr,faceted-search,Python,Sorting,Solr,Faceted Search,我有一个元组列表,如下所示,这是我从Solr得到的: [('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)] 请注意,不仅返回了第二、第三、第九和第十一个回路 我需要根据我拥有的一个排序元组对其进行排序,如下所示: COURT_ORDER = ( 'Supreme Court', 'First Circuit', 'Second Cir

我有一个元组列表,如下所示,这是我从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)]
有没有一种聪明的方法可以做到这一点


(如果可能的话,这需要用晒黑标签来标记,但我无法创建它,因为缺少分数。)

建立一个字典,将球场名称映射到所需的排名。然后使用查找法院名称的a进行排序,以查找排名:

>>> COURT_ORDER = (
    'Supreme Court',
    'First Circuit',
    'Second Circuit',
    'Third Circuit',
    'Fourth Circuit',
    'Ninth Circuit',
    'Eleventh Circuit',
)
>>> court_seq = dict(zip(COURT_ORDER, range(len(COURT_ORDER))))
>>> lot = [('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)]
>>> sorted(lot, key=lambda t: court_seq[t[0]])
[('Second Circuit', 34), ('Third Circuit', 4), ('Ninth Circuit', 24), ('Eleventh Circuit', 2)]

有关如何排序的详细信息,请参见。

根据其
[0]
项在
法庭命令中第一次出现的
索引

data = [('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)]
sorted(data, key = lambda x: COURT_ORDER.index(x[0]))

关于标记:我几乎看不出数据的来源与排序问题有什么关系。排序方面是其他使用Sunburnt库的人可能想做的事情,因此应该对其进行适当的标记,虽然我知道这主要是一个Python问题。Karl Mnechtels示例使用有序列表的索引意味着不再需要字典。@Paddy3118字典的O(1)查找时间是首选。为列表编制索引的速度很慢,而且很少采用正确的方法(tm)。