列表中所有匹配元素的位置 [英] Position of All Matching Elements in List

查看:245
本文介绍了列表中所有匹配元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Common Lisp编写一个类似于内置位置函数的函数,该函数返回大海捞针中与针相匹配的所有元素的位置列表,而不是第一个.我已经提出了一些可能的解决方案(例如,在位置上使用cdr-from函数递归搜索下一个元素,并将结果添加到上一个位置),但是到目前为止,我还没有提出任何方法看起来格外优雅.

I'm trying to write a function in Common Lisp similar to the built in position function, that returns a list of the positions of all elements in the haystack that match the needle, as opposed to just the first. I've come up with a few possible solutions (for example recursively searching for the next element using a cdr-from function on the position and adding the result to the previous position) but none of the approaches I've come up with so far seem particularly elegant.

由于我目前正在苦苦挣扎,有人可以提出解决此问题的最佳方法吗?

Can anyone suggest what would be the best way of approaching this, as I'm currently struggling.

推荐答案

解决问题的明显方法是依次查看列表中的每个元素,并且每次比较等于指针时都收集其位置进入输出列表.在这种情况下,获取位置非常容易,因为我们是从 haystack的开头开始的; 我们可以使用变量来计算从0开始的当前位置.

The obvious way to solve the problem is just to look at each element of the list in turn, and each time one compares as equal to the needle collect its position into an output list. Getting the position is very easy in this case, because we are starting from the beginning of haystack; we can use a variable to count the current position starting from 0.

因此,如果我们用句子描述完整的算法,我们会说类似为大海捞针中的每个元素查找大海捞针在干草堆中的所有位置,以及从0开始的位置(当元素等于针,收集位置."

So if we describe the full algorithm in a sentence, we'd say something like "to find all the positions of a needle in a haystack, for each element in the haystack, and the position starting from 0, when the element is equal to the needle, collect the position."

基本上,当您要进行迭代处理时,使用LOOP工具是正确的选择.即使在某些正式描述,它的语法很复杂. ="http://www.gigamonkeys.com/book/loop-for-black-belts.html" rel ="noreferrer">经验您几乎可以将算法的英语描述放在LOOP的主体,它将起作用.

The LOOP facility is basically the right thing to break out when you want to do iterative processing. Even though its syntax is complicated to describe formally, after some experience you can pretty much just put the English-language description of the algorithm in the body of LOOP and it will work.


(defun all-positions (needle haystack)
  (loop
    for element in haystack 
    and position from 0
     when (eql element needle)
      collect position))

这篇关于列表中所有匹配元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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