将 Scala 列表拆分为 n 个交错列表 [英] Split a scala list into n interleaving lists

查看:70
本文介绍了将 Scala 列表拆分为 n 个交错列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个List,例如

List(1, 2, 3, 4, 5, 6, 7)

将其拆分为 n 个子列表,以循环方式将项目放入每个列表的最佳方法是什么?

what is the best way to split it into n sub-lists, putting items into each list in a round-robin fashion?

例如如果 n = 3,结果应该是

e.g. if n = 3, the result should be

List(List(1, 4, 7), List(2, 5), List(3, 6))

我以为集合 API 中会有一种方法可以执行此操作,但我似乎找不到.

I thought there would be a method in the collections API to do this, but I can't seem to find it.

经典单线的奖励积分;)

Bonus points for classy one-liners ;)

推荐答案

scala> def round[T](l: List[T], n: Int) = (0 until n).map{ i => l.drop(i).sliding(1, n).flatten.toList }.toList
round: [T](l: List[T], n: Int)List[List[T]]

scala> round((1 to 7).toList, 3)
res4: List[List[Int]] = List(List(1, 4, 7), List(2, 5), List(3, 6))

这篇关于将 Scala 列表拆分为 n 个交错列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆