Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list of tuples f#

this should be really quick, I have a list of tuples like [("8585", 1);("9232",1);etc] where the second item corresponds to the number of ocurrences the item in "" makes. I was wondering how could i arrange my list from the one that makes more ocurrences to the one that makes least.

f#!

like image 453
Tomas Avatar asked Aug 19 '14 18:08

Tomas


People also ask

Can I sort a list of tuples?

If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key.

How do you sort tuples of tuples?

Using sorted() In Python, use the sorted() built-in function to sort a Tuple. The tuple should be passed as an argument to the sorted() function. The tuple items are sorted (by default) in ascending order in the list returned by the function. We can use a tuple to convert this list data type to a tuple ().

How do you sort the list of tuples by value?

Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element. Copied!

How do you sort a tuple to an order?

To sort a Tuple in Python, use sorted() builtin function. Pass the tuple as argument to sorted() function. The function returns a list with the items of tuple sorted in ascending order.


3 Answers

Use sortBy:

let lst = [("8585", 1);("9232",3)]
List.sortBy (fun (_, y) -> -y) lst
like image 88
Gus Avatar answered Oct 16 '22 01:10

Gus


Like Gustavo implied, if it's numeric, you can negate it to reverse its order in sorting. That's what the unary operator ~- is for.

Your peculiar choice of data, that is tuples of 'something * int, let me suspect that you are counting the number of certain occurences, and for that Seq.countBy may help (sorry, no list equivalent).

// Your key, Some data 
[  "9232",   false
   "8585",   false
   "9232",   true 
   "9232",   true ]
|> Seq.countBy fst
|> Seq.sortBy (snd >> (~-))

// val it : seq<string * int> = seq [("9232", 3); ("8585", 1)]

That's sorted by the count (snd element of the tuple) of the key (fst element of the tuple) negated.

like image 4
kaefer Avatar answered Oct 16 '22 02:10

kaefer


F# does have List.sortByDescending, so you could have:

[("8585", 1);("9232",3)]
|> List.sortByDescending (fun (_,y) -> y)
like image 1
ubersnack Avatar answered Oct 16 '22 01:10

ubersnack