开发者

Sorting a list of based on the 2nd element of a tuple

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 metho开发者_开发问答d for Lists to handle this or how does one do this?

Thanks


The function lists:keysort/2 fits like glove for this.

1> lists:keysort(2, [{a,b},{b,a},{b,b}]).

[{b,a},{a,b},{b,b}]

2> lists:keysort(2, [{1,14},{3,10},{2,13}]).

[{3,10},{2,13},{1,14}]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜