如何在 Groovy 中将列表拆分为大小相等的列表?
如果我有这个:
def array = [1,2,3,4,5,6]
是否有一些内置功能可以让我执行此操作(或类似的操作):
array.split(2)
并获取:
[[1,2],[3,4],[5,6]]
?
If I have this:
def array = [1,2,3,4,5,6]
Is there some built-in which allows me to do this ( or something similar ):
array.split(2)
and get:
[[1,2],[3,4],[5,6]]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
我一直在寻找同样的问题,并且发现列表的
collate()
方法非常有用。此处是文档的链接。
I was looking for the same problem and I found the
collate()
method for lists to be very useful.Here is the link to the documentation.
没有内置的东西可以做到这一点,但编写起来并不难:
There is nothing builtin to do that but it is not hard to write:
这是一个替代版本,它使用 Groovy 的动态功能向 List 类添加 split 方法,它可以满足您的期望:
Here's an alternative version, that uses Groovy's dynamic features to add a split method to the List class, that does what you expect:
我知道这是非常旧的 - 但对于那些希望将列表分成相等的分区(带有余数)的人,并且您错过了 Tim 对原始帖子的评论,最新的常规方法是 List 对象的 collate() 方法,该方法已被从 Groovy 1.8.6 开始可用。
I know this is super old - but for those looking to split a list into equal partitions (with remainders), and you miss Tim's comment on the original post, the most recent groovy way is the collate() method for List objects that has been available since Groovy 1.8.6.
这个问题很老了,但无论如何我想分享我想出的将列表拆分为相等大小的列表的方法。
list.collate
很棒,但对我来说不起作用,因为我需要均匀地分割列表。我在哪里做:
This question is old, but I want to share anyway what I came up with to split a list in equal sized lists.
list.collate
is great, but did not work for me, as I needed the lists to be split evenly.Where is what I do:
我的groovy很旧而且我没有柯林特。我实现了一个小型递归函数,其工作原理类似于Java中的Lists.partition,
其工作原理如下
My groovy is old and I don't have colide. I've implemented a small recursive function that works like Lists.partition from Java
which works like
编辑从 groovy 1.8.6 开始,您可以使用整理
另一种使用注入和元类的方法
编辑:修复了空列表的问题
EDIT As of groovy 1.8.6 you can use the collate method on lists
Another method using inject and metaClasses
Edit: fixed an issue with the empty list
我同意 Chris 的观点,groovy 中没有内置任何东西来处理这个问题(至少对于两个以上的分区),但我将你的问题解释为提出了与他不同的问题。这是一个实现我认为您所要求的功能:
I agree with Chris that there isn't anything built into groovy to handle this (at least for more than 2 partitions), but I interpreted your question to be asking something different than he did. Here's an implementation that does what I think you're asking for:
查看 groovy 1.8.6。 List 上有一个新的整理方法。
请查看 Groovy List 文档 了解更多信息,因为还有一些其他参数可以为您提供一些其他选项,包括删除其余部分。
Check out groovy 1.8.6. There is a new collate method on List.
Take a look at the Groovy List documentation for more info because there are a couple of other params that give you some other options, including dropping the remainder.