如何对嵌套列表中的每个列表求和? [英] How to sum each list in a nested list?

查看:130
本文介绍了如何对嵌套列表中的每个列表求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的基本上是获取列表中的一些列表,如果有意义的话.

What I am trying to do is basically get the some of the list of list, if that makes sense.

我想要实现的是sum([[1, 2], [3, 4], [5, 6]]).应该返回:

What I am trying to achieve is sum([[1, 2], [3, 4], [5, 6]]). Should return:

Number Of Lists: 3
List 1
3
List 2
7
List 3
11....etc

我可以获得相当简单的列表数量,但我不太确定如何遍历列表,然后为每个列表添加数字.我是否让这比实际情况更复杂?

I can get the Number of Lists which is fairly simple but I'm not quite sure how to loop through the List and then for each List add the number up. Am I making this more complicated than it actually is?

推荐答案

在 SWI-Prolog 中你可以使用 maplistsumlist;

In SWI-Prolog you can use maplist and sumlist;

?- maplist(sumlist, [[1,2], [3,4], [5,6]], Lengths).
Lengths = [3, 7, 11].

现在您可以按照自己喜欢的方式漂亮地打印Lengths.

Now you can pretty-print Lengths the way you like.

要了解maplistsumlist 是如何实现的,只需调用listing(maplist)listing(sumlist).

To learn how maplist and sumlist are implemented, just call listing(maplist) and listing(sumlist).

这篇关于如何对嵌套列表中的每个列表求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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