简体   繁体   English

如果我想按一个标准升序排序并按另一个标准降序排序,我该如何使用 sort 函数?

[英]How can i use the sort function if i want to sort ascending by a criterion and descending by another criterion?

I am trying to implement the A* algorithm in Python as a learning exercise.我正在尝试在 Python 中实现 A* 算法作为学习练习。 I have a list of nodes, called open , that contains strings that represent the names of graph nodes.我有一个名为open的节点列表,其中包含表示图形节点名称的字符串。 Example: open["node_a", "node_b", "node_c"] .示例: open["node_a", "node_b", "node_c"] I also have two defaultdict dictionaries, f_estim and g , that contain values like {"name_of_node" : integer_representing_a_certain_cost_associated_to_the_node} .我还有两个defaultdict字典f_estimg ,它们包含{"name_of_node" : integer_representing_a_certain_cost_associated_to_the_node} I am required to sort the open list ascending by the value associated in f_estim , and if that value is equal for two nodes, descending according to the value in g .我需要按f_estim关联的值对open列表进行升序排序,如果两个节点的值相等,则根据g的值降序。 I am sorting ascending like so: open.sort(key=lambda node: f_estim[node]) .我按升序排序: open.sort(key=lambda node: f_estim[node]) How can i also sort descending when reaching two equal values?当达到两个相等的值时,我如何还降序排序? I could not find the answer in the documentation of the sort function.我在sort函数的文档中找不到答案。 Thank you!谢谢!

你可以这样做:

open.sort(key=lambda node: (f_estim[node], -g[node]))

暂无
暂无

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

相关问题 如何按升序或降序对 matplotlib 图进行排序? - How can i sort the matplotlib graph in ascending or descending order? 我如何按 seaborn 的升序/降序对直方图条进行排序? - How i can sort histogram bar in ascending/descending order of seaborn? 我如何添加另一个简单的 function 以添加两个选项以按数字升序和降序对此代码进行排序? - how do i add another simple function to add two more options to sort this code numerically ascending and descending? 我想按数字降序对字典进行排序,然后按字母顺序升序 - I want to sort a dictionary descending by number and then ascending alphabetically 我不能使用sorted函数对两个元素元组列表按降序排列,然后在出现领带的情况下按字母升序排序 - I can't use the sorted function to sort a two elements tuple list in descending numerical order then in ascending alphabetical order in case of a tie 如何按键升序和值降序对字典进行排序? - How do I sort a dictionary by key ascending & value descending? 如何按第二项降序和第一项升序对列表进行排序? - How can i sort a list by the second item descending and first one ascending? 如何根据特定标准对列表进行排序 - how to sort list according certain criterion 如何对三个 Vals 的压缩列表进行排序,其中我想要前两个反转(降序)而第三个不是(升序)? - How do I Sort a Zipped List of Three Vals where I want first two Reversed (Descending) and Third is not (Ascending)? 如何按升序对python进行排序? - How can I sort in python in ascending order?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM