获得序列中一个项目的出现的位置 [英] getting the positions of the occurrences of one item in a sequence
问题描述
从aa序列,我需要获取给定项目出现的所有位置。
From a a sequence, I need to fetch all the positions of the occurrence of a given item.
我问自己,如果这是一个很好的方法来解决问题:
I'm asking myself if this is a good way to solve the problem:
(defn get-positions [item coll]
(->> (map-indexed vector coll)
(filter (fn [[_ v]] (= item v)))
(map first)))
这也适用于字符串,它们将被第一个映射转换为序列。但是,如果我知道输入是字符串,这个问题会有更多的字符串特定的方法吗?
This also works for strings, they'll be transformed to a sequence by the first map. However, if I know the input's are strings, would there be a more string specific approach for this problem?
推荐答案
有一个一般的解决问题的方法,你为什么要花更多的精力去设想一个更具体的一个?
Since you already have a general solution to the problem, why would you want to spend more effort to try to come up with a more specific one? The benefits of doing so here are negligible.
只是出于种种原因,这里是另一种实现你的函数的方法:
Just for variety's sake, here's another way to implement your function:
(defn positions [x coll]
(keep-indexed #(when (= x %2) %1) coll))
这篇关于获得序列中一个项目的出现的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!