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

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

问题描述

我有一本字典,并希望把它转换成一个列表。然后,我想根据第二个元素(Value),将由{Key,Value}对组成的列表排序从最小到最大。



是否有内置排序方法用于列表处理这个或如何做到这一点?



谢谢

解决方案

通过第二个元素排序的最简单的方法是定义自己的排序功能,可以按如下方式进行排序:

  fun({KeyA,ValA},{KeyB,ValB}) - > {ValA,KeyA} =< {ValB,KeyB}结束。 

并在列表中调用:sort / 2

  1>列表: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中的密钥将用于对值相同的条目进行排序。


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?

Thanks

解决方案

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.

And call it in 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}]

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天全站免登陆