更绝妙的列表操作方式
我有两个这样的列表:
def a = [100,200,300]
def b = [30,60,90]
我想要像这样操作 a
的 Groovier 方式:
1) a
的第一个元素应该更改为 a[0] -2*b[0]
2)a
的第二个元素应更改为a[1]-4*b[1]
3)第三个元素a
应该更改为 a[2]-8*b[2]
(前提是 a
和 b
的长度与 >3
)
如果列表像这样更改为 map
,我们可以说:
def a1 = [100:30, 200:60, 300:90]
在这种情况下如何执行与上述相同的操作。
提前致谢。
I have two list like this :
def a = [100,200,300]
def b = [30,60,90]
I want the Groovier way of manipulating the a
like this :
1) First element of a
should be changed to a[0]-2*b[0]
2)Second element of a
should be changed to a[1]-4*b[1]
3)Third element of a
should be changed to a[2]-8*b[2]
(provided that both a
and b
will be of same length of 3
)
If the list changed to map
like this, lets say:
def a1 = [100:30, 200:60, 300:90]
how one could do the same above operation in this case.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于
List
,我会选择:对于
Map
,它更容易一些,但仍然需要外部状态:遗憾的是,Groovy 没有
zip
,在本例中 - 类似于zipWithIndex
或collectWithIndex
。For
List
, I'd go with:For
Map
it's a bit easier, but still requires an external state:A pity, Groovy doesn't have an analog for
zip
, in this case - something likezipWithIndex
orcollectWithIndex
.使用收集
响应 Victor 的评论,您可以使用收集来完成此操作
使用注入
您还可以使用
注入
,传入乘数和结果的映射,然后在最后取出结果:类似地,您可以对映射使用注入:
使用
inject
的优点是不需要声明外部变量,但缺点是难以阅读代码(正如 Victor 指出的那样)在注释中,这对代码进行了静态分析对于 IDE 和 groovypp 来说很难甚至不可能)Using collect
In response to Victor in the comments, you can do this using a collect
Using inject
You can also use
inject
, passing in a map of multiplier and result, then fetching the result out at the end:And similarly, you can use inject for the map:
Using
inject
has the advantage that you don't need external variables declared, but has the disadvantage of being harder to read the code (and as Victor points out in the comments, this makes static analysis of the code hard to impossible for IDEs and groovypp)