[英]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_estim
和g
,它们包含{"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.