gpt4 book ai didi

lisp - 将列表中每个列表的第三个元素相加

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:25 24 4
gpt4 key购买 nike

我目前有这样一个列表:

((map 9 150) (compass 13 35) (water 150 240) (sandwich 50 16) (rope 50 49))

我正在尝试遍历此列表以获取粗体值并给出这些值的总和。我一直在查看 car 和 cdr,但我似乎无法获得这些值。有没有简单的方法可以做到这一点?

最佳答案

这将是列表中的 third 值或 caddr。因此

(mapcar #'third products) ; ==>  (150 35 240 16 49)

如果你的列表很小,你可以使用 apply:

(apply #'+ (mapcar #'third products)) ; ==> 490

对于更大的列表(超过 1000),我建议使用 reduce

(reduce #'+ (mapcar #'third products)) ; ==> 490

使用reduce你可以使用:key来避免mapcar:

(reduce #'+ products :key #'third)     ; ==> 490

你也可以使用循环:

(loop :for element :in products 
:sum (third element)) ; ==> 490

关于lisp - 将列表中每个列表的第三个元素相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29351108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com