Lisp两个列表相乘并相加两个值

Lisp两个列表相乘并相加两个值

本文介绍了Lisp两个列表相乘并相加两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,每个列表中都有一个列表.我想每次从第一个列表中获取第三个值,然后从第二个列表中获取第一个值,将这些项相乘,然后将它们相加即可.

I have two lists, each list has lists inside of them. I want to get the third value from the first list and the first value from the second list each time, multiply these items and then add them to sum.

(defvar *list-1* ((item1 1 4) (item2 4 5) (item3 5 8)))
(defvar *list-2* ((1) (3) (5)))

所以我要(1 * 4)+(3 * 5)+(5 * 8)= 59

So I want (1*4) + (3*5) + (5*8) = 59

到目前为止,我拥有以下代码

I have the below code so far

(defun get-total (lst lst1)
  (loop :for element :in lst
        :for element1 :in lst1
        :sum (third element)))

推荐答案

循环可以为您进行一些破坏,因此您甚至不需要调用 third ,但可以在第一个列表中循环(无n a),这会将 a 绑定到第三个值.您可以对第二个列表执行相同的操作,但使用销毁列表列表(b)除外.然后您将拥有:

loop can do some destructuring for you, so you don't even need to call third, but can just loop for (nil nil a) in the first list, which will bind a to the third value. You can do the same thing with the second list, except with a destructuring list list (b). Then you'd have:

(loop :for (nil nil a)  :in '((item1 1 4) (item2 4 5) (item3 5 8))
      :for (b)          :in '((1) (3) (5))
      :summing (* a b))
;=> 59

这篇关于Lisp两个列表相乘并相加两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:19