根据元组的第二个元素对列表进行排序 [英] Sorting a list of based on the 2nd element of a tuple

查看:37
本文介绍了根据元组的第二个元素对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,想把它转换成一个列表.然后我想根据第二个元素(值)对包含 {Key, Value} 对的结果列表从 min 到 max 进行排序.

I have a dictionary and want to convert it to a list. Then I would like to sort the resulting list consisting of {Key, Value} pairs from min to max depending on the 2nd element(Value).

列表是否有内置的排序方法来处理这个问题,或者如何做到这一点?

Is there a built in sort method for Lists to handle this or how does one do this?

谢谢

推荐答案

按第二个元素排序的最简单方法是定义自己的排序函数,其工作方式如下:

The easiest way to sort by the second element would be to define your own sorting function that could work as follows:

fun({KeyA,ValA}, {KeyB,ValB}) -> {ValA,KeyA} =< {ValB,KeyB} end.

并在 lists:sort/2 中调用它:

1> lists:sort(fun({KeyA,ValA}, {KeyB,ValB}) -> {ValA,KeyA} =< {ValB,KeyB} end., [{a,b},{b,a},{b,b}]).
[{b,a},{a,b},{b,b}]

这是因为 Erlang 总是会自动比较元组从第一个元素到最后一个元素.此函数交换第一个和第二个元素,因此第二个元素充当第一个比较点.然后,您的 dict 中的 Key 将用于对值相同的条目进行排序.

This is because Erlang will always automatically compare tuples from first to last element. This function swaps the first and the second element so the second one acts as the first point of comparison. The Key in your dict will then be used to order entries where values are the same.

这篇关于根据元组的第二个元素对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆