简体   繁体   English

在Python中,使用sorted()方法是否可以通过优先级字段对字典列表进行排序?

[英]In Python, using the sorted() method, is it possible to sort a list of dictionaries by a priority field?

I have a list of dictionaries and I sort them by multiple keys in a given order (1st 'Name', 2nd 'Start' and 3rd 'End'): 我有一个字典列表,并按给定顺序(第一个“名称”,第二个“开始”和第三个“结束”)按多个键对它们进行排序:

sorted_list = sorted(list, key=lambda dict: (dict['Name'], dict['Start'], -dict['End']))

I want the last sorting is done by a priority field: 我希望最后排序由优先级字段完成:

the dict['Status'] is a string name like "gene", "mRNA", "exon" and "CDS". dict['Status']是一个字符串名称,例如“ gene”,“ mRNA”,“ exon”和“ CDS”。 The name "gene" must be higher than the others and "CDS" lower than the others. 名称“ gene”必须高于其他名称,而“ CDS”必须低于其他名称。

Thanks for your answer, 感谢您的回答,

First advice: don't use builtin-names as variable-names. 首要建议: 不要将内置名称用作变量名称。 You will be confused like hell when you try to use them later. 当您稍后尝试使用它们时,您会感到很困惑。 Eg 例如

 dict = [1, 2, 3]
 d = dict(a="b")

will fail miserably. 会惨败。 So - never call variables list, dict, file, str, int and all the others. 所以-永远不要调用变量list,dict,file,str,int和其他所有变量。

Your actual problem is solved by a simple lookup-table: 您的实际问题可以通过一个简单的查找表解决:

priorities = dict(gene=0, CDS=1000)
sorted_list = sorted(list, 
        key=lambda d: (d['Name'], d['Start'], -d['End'], 
        priorities.get(d['Status'], 1)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM