import Data.List(groupBy, sortBy)
import Data.Ord(compare)
groupBy (\x y -> x!!1==y!!1) $ sortBy (\x y -> compare (x!!1) (y!!1)) [[0,1],[2,2],[0,2],[1,1]]
[[[0,1],[1,1]],[[2,2],[0,2]]]
,或者更改索引訪問將持續
groupBy (\x y -> last x==last y) $ sortBy (\x y -> compare (last x) (last y)) [[0,1],[2,2],[0,2],[1,1]]
[[[0,1],[1,1]],[[2,2],[0,2]]]
也許更容易一些輔助功能
compareLast x y = compare (last x) (last y)
equalLast x y = EQ == compareLast x y
groupBy equalLast $ sortBy compareLast [[0,1],[2,2],[0,2],[1,1]]
[[[0,1],[1,1]],[[2,2],[0,2]]]
或者,再往前一步
compareBy f x y = compare (f x) (f y)
equalBy f = ((EQ ==) .) . compareBy f
partitionBy f = groupBy (equalBy f) . sortBy (compareBy f)
partitionBy last [[0,1],[2,2],[0,2],[1,1]]
[[[0,1],[1,1]],[[2,2],[0,2]]]
這不看起來像一個Python問題。 – Mumbleskates
http://stackoverflow.com/questions/12398458/how-to-group-similar-items-in-a-list-using-haskell – alamar