我们具有以下数字序列:[19、23、24、31、126、127、155、159、160、161]。我们需要根据相邻值之间的差异对该序列进行分组,以便如果组大小> 1,则每个组中值的差异将等于1。
在Python中,我将编写类似以下内容的内容:
outliers = [19, 23, 24, 31, 126, 127, 155, 159, 160, 161]
chains = [[i for i in list(map(itemgetter(1), g))]
for _, g in itertools.groupby(enumerate(outliers),
lambda x: x[0]-x[1])]
# [[19], [23, 24], [31], [126, 127], [155], [159, 160, 161]]
挺整洁的。但是,如何在Scala中做到这一点而又不陷入条件循环呢?到目前为止,我一直在尝试使用zipWithIndex
和groupBy
方法做某事:(
您可以fold
遍历整个序列,随时进行构建结果。
outliers.foldRight(List.empty[List[Int]]) {case (n, acc) =>
if (acc.isEmpty) List(List(n))
else if (acc(0)(0) == n+1) (n :: acc.head) :: acc.tail
else List(n) :: acc
}
//res0: List[List[Int]] = List(List(19), List(23, 24), List(31), List(126, 127), List(155), List(159, 160, 161))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句