在给定某些条件的情况下,如何将列表嵌入到 Groovy 中的列表中?
我有一个像这样的常规代码:
main = []
b="ogodtsneeencs"
def input = ["go", "good", "do", "sentences", "tense", "scen"]
(0..(input.size()-1)).each{ Sp(input[it]) }
def Sp(def a)
{
flag = false
list = []
(0..(a.size()-1)).collect { list << a[it] }
ans = list.permutations().each { temp = it.join()
if(b.find("$temp"))
{
main << it
flag = true
}
}
if(flag == false)
main << null
}
println main
其输出:
[[o, g], [g, o], [o, g, o, d], [o, d], [t, s, n, e, e, e, n, c, s], [t, s, n, e, e], [e, n, c, s]]
我在这里做的事情是使用 input
查找 b
中发生的可能排列。我正在根据需要获得输出。但如果仔细观察输出,对于相同的输入 go
ie(input[0]
) 会产生前两个输出,即 main[0] 和 main[ 1]
。由于要以某种方式保留索引(即生成哪个 input
哪个输出 main
),我如何更改上面的代码,以便输出像这样返回:
[[[o, g], [g, o]], [o, g, o, d], [o, d], [t, s, n, e, e, e, n, c, s], [t, s, n, e, e], [e, n, c, s]]
指示前两个输出与同一输入相同,在我们的例子中为 input[0]
。
提前致谢。
I have a groovy code like this :
main = []
b="ogodtsneeencs"
def input = ["go", "good", "do", "sentences", "tense", "scen"]
(0..(input.size()-1)).each{ Sp(input[it]) }
def Sp(def a)
{
flag = false
list = []
(0..(a.size()-1)).collect { list << a[it] }
ans = list.permutations().each { temp = it.join()
if(b.find("$temp"))
{
main << it
flag = true
}
}
if(flag == false)
main << null
}
println main
which outputs :
[[o, g], [g, o], [o, g, o, d], [o, d], [t, s, n, e, e, e, n, c, s], [t, s, n, e, e], [e, n, c, s]]
The thing I'm doing here is to find the possible permutations that have occurred in b
using the input
. And I'm getting the output as needed. But if the output is noticed carefully, for the same input go
i.e(input[0]
) produces the first two outputs i.e main[0] and main[1]
. Since to keep a index kind of way(i.e for which input
which output main
is produced), how I can change the above code, so that the output returns like this :
[[[o, g], [g, o]], [o, g, o, d], [o, d], [t, s, n, e, e, e, n, c, s], [t, s, n, e, e], [e, n, c, s]]
Indicating that the first both outputs is same from same input, in our case it is input[0]
.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Artur 的解决方案可以进一步改进为:
Artur's solution can be further groovified to:
我还稍微简化了您的代码:
这将输出:
如果您希望拥有所有没有封闭集的单例集(正如您在示例中所写,尽管我发现它有点不切实际),那么您可以只需将
Sp
的最后一行交换为:I've also simplified your code a bit:
This would output:
If you'd like to have all the singleton sets without the enclosing set (as you wrote in your example, although I find it as a bit impractical), then you can just swap the last line of
Sp
to: