繁体   English   中英

如何将2d列表除以最后一个元素haskell?

[英]how to divide a 2d list by last element haskell?

我试图基于Haskell中每个列表中的最后一个元素将列表按2dlist分组。 像这样:

[[0,1],[2,2],[0,2],[1,1]]

可能会变成这样的3D列表:

[[[0,1],[1,1]],[[0,2],[2,2]]]

或使用任何数据结构将数据分为n个类别。

具体来说,我正在尝试在本教程中实现seperateByClass方法http://machinelearningmastery.com/naive-bayes-classifier-scratch-python/

目标是转换

def separateByClass(dataset):
    separated = {}
    for i in range(len(dataset)):
        vector = dataset[i]
        if (vector[-1] not in separated):
            separated[vector[-1]] = []
        separated[vector[-1]].append(vector)
    return separated


dataset = [[1,20,1], [2,21,0], [3,22,1]]
separated = separateByClass(dataset)
print('Separated instances: {0}').format(separated)

有输出

Separated instances: {0: [[2, 21, 0]], 1: [[1, 20, 1], [3, 22, 1]]}

哈斯克尔。 这是Data.MapfromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map ka的完美用例,它需要一个键列表-值对和当两个对碰巧共享同一键时组合值的策略。

λ> import Data.Maybe
λ> import Data.Map
λ> let last_ = listToMaybe . reverse
λ> let pairs = [(last_ x, [x]) | x <- dataset]

λ> fromListWith (\a b -> b) pairs
fromList [(Just 0,[[2,21,0]]),(Just 1,[[1,20,1]])]

λ> fromListWith (++) pairs
fromList [(Just 0,[2,21,0]),(Just 1,[3,22,1,1,20,1])]

λ> fromListWith (++) pairs
fromList [(Just 0,[[2,21,0]]),(Just 1,[[3,22,1],[1,20,1]])]

干得好,Haskell。

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]]]

或者,将索引访问更改为last

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]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM