Groovy中2列表的内容求和 [英] Sum the content of 2 list in Groovy

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

问题描述

我在 Groovy 中有两个列表,需要对两者的内容求和.

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

例如:

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

我期望这个结果:

total = [2,2,2]

<小时>

我尝试用 + 运算符 o .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 足够 groovy 还是我需要循环列表的每个元素?

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

推荐答案

Groovy 的 List.transpose() 在其他一些语言中的作用类似于 zip.试试这个:

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]

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

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