总和2名单在Groovy内容 [英] Sum the content of 2 list in Groovy

查看:183
本文介绍了总和2名单在Groovy内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列出了Groovy和需要总结两者的内容。

I have two lists in Groovy and need to sum the contents of both.

例如:

list1 = [1,1,1]
list2 = [1,1,1]

我预期这个结果:

I expected this result:

total = [2,2,2]


我试着用+操作Ø的.sum方法进行总结,但我有名单的串联。


I try to sum with + operator o .sum method, but I have a concatenation of the lists.

[1, 1, 1, 1, 1, 1]

这是很时髦的Groovy或者我需要循环列表中的每个元素?

It's Groovy enough groovy or I need to loop each element of the lists?

推荐答案

Groovy的的 List.transpose() 就像拉链中一些其他语言。试试这个:

Groovy's List.transpose() works like zip in some other languages. Try this:

list1 = [1,2,3]
list2 = [4,5,6]
assert [list1, list2].transpose()*.sum() == [5,7,9]

这篇关于总和2名单在Groovy内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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