如何从具有 2 个元素的子列表中添加元素(第一个元素是字符串,第二个元素是数字)? [英] How to add elements from sublists with 2 elements (the first element is a string and the second one a number)?
本文介绍了如何从具有 2 个元素的子列表中添加元素(第一个元素是字符串,第二个元素是数字)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理一个包含子列表的列表,每个子列表有 2 个元素.每个子列表的第一个元素是一个字符串,第二个元素是一个数字.
I'm working on a list that contains sublists with 2 elements each. The first element of each sublist is a string and the second one a number.
[ [e, 30], [a, 170], [k, 15], [e, 50] ]
我想添加每个子列表的所有数字.我试过这个:
I want to add all the numbers of each sublist. I tried this one:
sum_fire([H|T],S):-
flatten(H,L),
sum_fire(T,S),
L=[_H1|T1],
sum(T1,S).
但我认为这是完全错误的.我怎样才能让它工作?
but it's completely wrong, I think. How can i get this to work?
推荐答案
你只需要将字符串与数字分开:
You just need to break out the string versus the number:
sum_fire( [[_,N]|Tail], Sum ) :-
sum_fire( Tail, S1 ),
Sum is N + S1.
sum_fire( [], 0 ).
所以我使用 [_,N]
而不是 H 作为头部项目,因为我想要里面的东西(数字 N).我不关心和的字符串,所以它是 _
.
So I'm using [_,N]
instead of H for the head item because I want what's inside (the number N). I don't care about the string for the sum, so it's _
.
这篇关于如何从具有 2 个元素的子列表中添加元素(第一个元素是字符串,第二个元素是数字)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文