【问题标题】:Alternative to .indexOf to get the indices of a vector in Clojure替代 .indexOf 在 Clojure 中获取向量的索引
【发布时间】:2015-12-19 23:45:06
【问题描述】:

这是一个简单的问题,但我还是被卡住了。所以假设我有一个包含负数、零和正数的输入向量。

[-1 -1 -2 -1 -4 0 -6 -1 -5 -2 -10 **4** -12 -4 -6 -1 -16 **3** -18 **2** -10 -8 -22 **12** -19
-10 -14 0 -28 **12** -30 -1 -18 -14 -22 **19** -36 -16 -22 **10** -40 **12** -42 -4 -12 -20 -46 **28** -41 -7]

我想返回一个包含先前向量索引的向量,其中值为正数。

所以返回值是

 (11 17 19 23 29 35 39 41 47)

11 是 4 所在位置的索引,17 是 3 所在位置的索引,等等

我正在使用 .indexOF

这就是它返回的内容: (11 17 19 23 23 35 39 23 47)

我发现 b/c 在索引 23 处,正值是 12,在索引 29 处,值也是 12,所以它只是返回它第一次看到正值“12”的索引但是如何我可以解决这个问题吗?

我已阅读线程How do I find the index of an item in a vector? 但是我仍然在苦苦挣扎,因为如果您专门寻找“二”,那似乎在谈论如何在向量中找到“二”的索引。

【问题讨论】:

    标签: vector clojure indexof indices


    【解决方案1】:

    你可以使用keep-indexed:

    (keep-indexed (fn [idx v] (if (pos? v) idx)) input-vector)
    

    【讨论】:

      【解决方案2】:

      如果您正在搜索向量的正参数的索引号,您还可以使用map-indexed,它为您提供索引从 0 到 (dec (count your-vector)) 的参数,并结合 (filter pos?) 过滤掉您的正条目向量。 filter 函数通过您的向量并过滤满足其谓词先决条件的数字(在这种情况下它们应该是正数),然后您可以轻松地询问您刚刚使用 map-indexed 创建的索引:

      (defn indexof [a]
        (->> a
          (map-indexed vector)
          (filter #(pos? (second %)))
          (map first)))
      
      (indexof [-1 -1 -2 -1 -4 0 -6 -1 -5 -2 -10 4 -12 -4 -6 -1 -16 3 -18 2 -10 -8 -22 12 -19
       -10 -14 0 -28 12 -30 -1 -18 -14 -22 19 -36 -16 -22 10 -40 12 -42 -4 -12 -20 -46 28 -41 -7])
      
      => (11 17 19 23 29 35 39 41 47)
      

      如果搜索零,只需将filter 的谓词更改为zero? 即可搜索零:

      (defn indexof-zero [a]
        (->> a
          (map-indexed vector)
          (filter #(zero? (second %)))
          (map first)))
      
      (indexof-zero [-1 -1 -2 -1 -4 0 -6 -1 -5 -2 -10 4 -12 -4 -6 -1 -16 3 -18 2 -10 -8 -22 12 -19
      -10 -14 0 -28 12 -30 -1 -18 -14 -22 19 -36 -16 -22 10 -40 12 -42 -4 -12 -20 -46 28 -41 -7])
      
      => (5 27)
      

      【讨论】:

        猜你喜欢
        • 2014-09-19
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多