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#!
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.
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 ().
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!
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.
Use sortBy:
let lst = [("8585", 1);("9232",3)]
List.sortBy (fun (_, y) -> -y) lst
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.
F# does have List.sortByDescending, so you could have:
[("8585", 1);("9232",3)]
|> List.sortByDescending (fun (_,y) -> y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With