Groovy:从两个范围创建二维数组 [英] Groovy: create a two-dimensional array from two ranges

查看:632
本文介绍了Groovy:从两个范围创建二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建这个:

[ [ 1, 1 ], [ 1, 2 ], [ 1, 3 ], [ 2, 1 ] ... [ 6, 3 ]]

使用GroovyConsole,我正在尝试如下操作:

Using GroovyConsole I've being trying stuff like this:

def blob = (1..6).collect{ i ->
  (1..3).collect{ j ->
    [ i, j ]
  }
}
println "$blob ${blob.class.simpleName}"

...,您可能会猜到对flatten的调用的各种排列.

... with various permutations of calls to flatten, as you might surmise.

有没有办法做到这一点?

Is there a way to achieve this?

推荐答案

使用combinations方法更容易:

l1 = [1,2,3,4,5,6]
l2 = [1,2,3]
[l, l2].combinations()

哪个输出:

[[1, 1], [2, 1], [3, 1], [4, 1], [5, 1], [6, 1], [1, 2], [2, 2], 
 [3, 2], [4, 2], [5, 2], [6, 2], [1, 3], [2, 3], [3, 3], [4, 3], 
 [5, 3], [6, 3]]

这篇关于Groovy:从两个范围创建二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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