如何根据索引从序列中过滤元素

如何根据索引从序列中过滤元素

本文介绍了如何根据索引从序列中过滤元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序列 s 和该序列 indexes 的索引列表.如何仅保留通过索引给出的项目?

I have a sequence s and a list of indexes into this sequence indexes. How do I retain only the items given via the indexes?

简单的例子:

(filter-by-index '(a b c d e f g) '(0 2 3 4)) ; => (a c d e)

我的用例:

(filter-by-index '(c c# d d# e f f# g g# a a# b) '(0 2 4 5 7 9 11)) ; => (c d e f g a b)

推荐答案

列出包含与索引结合的项的向量列表,

make a list of vectors containing the items combined with the indexes,

(def with-indexes (map #(vector %1 %2 ) ['a 'b 'c 'd 'e 'f] (range)))
#'clojure.core/with-indexes
 with-indexes
([a 0] [b 1] [c 2] [d 3] [e 4] [f 5])

过滤此列表

lojure.core=> (def filtered (filter #(#{1 3 5 7} (second % )) with-indexes))
#'clojure.core/filtered
clojure.core=> filtered
([b 1] [d 3] [f 5])

然后删除索引.

clojure.core=> (map first filtered)
(b d f)

然后我们将其与"thread last"宏一起线程化

then we thread it together with the "thread last" macro

(defn filter-by-index [coll idxs]
    (->> coll
        (map #(vector %1 %2)(range))
        (filter #(idxs (first %)))
        (map second)))
clojure.core=> (filter-by-index ['a 'b 'c 'd 'e 'f 'g] #{2 3 1 6})
(b c d g)

故事的寓意是将其分解成小的独立部分,对其进行测试,然后将其组合成一个有效的功能.

The moral of the story is, break it into small independent parts, test them, then compose them into a working function.

这篇关于如何根据索引从序列中过滤元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:50