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

时间:2011-11-27 07:56:50

标签: 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 Circuit',
    'Third Circuit',
    'Fourth Circuit',
    ...and so on...,
)

排序后所需的输出为:

 [('Second Circuit', 34), ('Third Circuit', 4), ('Ninth Circuit', 24), ('Eleventh Circuit', 2)]

有一种聪明的方法吗?

(如果可能的话,这需要使用Sunburnt标签进行标记,但由于缺少点数,我无法创建它。)

2 个答案:

答案 0 :(得分:4)

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

>>> 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)]

有关如何排序的更多见解,请参阅Sorting HOWTO

答案 1 :(得分:2)

key根据index[0]项首次出现的COURT_ORDER项:

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