I have a list of lists, let's say:
import Data.List
xs = [[1,2], [1,2,3], [2,3]]
I want to get the inner list with the most items, in this case [1,2,3]
.
I'm trying to use the maximumBy
function from the Data.List
library:
maximumBy (compare `on` length) xs
but I get the following error: not in scope 'on'
Can anyone tell me what is wrong, or if you have a better way to get the list?
Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.
Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.
To get the length of a list in Python, you can use the built-in len() function. Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list.
Method 1: Compare Two Lists Using Equal Sign Operator Method 2: Match Data by Using Row Difference Technique Method 3: Match Row Difference by Using IF Condition Method 4: Match Data Even If There is a Row Difference
As a consequence, by sorting the lists first we ensure that both lists will have the same order, and thus can be compared using the == operator. Contrary to lists, sets in Python don’t care about order. For example, a set {1, 2, 3} is the same as {2, 3, 1}. As such, we can use this feature to compare the two lists ignoring the elements’ order.
Find Length of a Linked List (Iterative and Recursive) Write a function to count the number of nodes in a given singly linked list. For example, the function should return 5 for linked list 1->3->1->2->1. 1) Initialize count as 0 2) Initialize a node pointer, current = head.
The len () method offers the most used and easy way to find length of any list. This is the most conventional technique adopted by all the programmers today. # Python program to demonstrate working # of len ()
or you can make it a bit more explicit:
xs = [[1,2],[1,2,3],[2,3]]
ordLen a b = compare (length a) (length b)
maximumBy ordLen xs
maybe it's easier to understand this way.
on
is defined in Data.Function, so you need to import that.
Alternatively, you can use comparing
from Data.Ord:
maximumBy (comparing length) xs
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