【问题标题】:how can you interleave two vectors of differing lengths in clojure如何在 clojure 中交错两个不同长度的向量
【发布时间】:2014-07-03 21:07:24
【问题描述】:

n+1n 成员交错两个向量的最简单方法是什么?

(def a [:a :c :e])
(def b [:b :d])
(interleave a b ); truncates to shortest list
[:a :b :c :d]

;what I would like. 
(interleave-until-nil a b)
[:a :b :c :d :e]

【问题讨论】:

  • 在这种特定情况下,您可以这样做(concat (interleave a b) [(last a)])
  • @zack 你会在向量上有不同的长度吗?您的示例显示了一个,但如果您想要通用的东西来处理任意长度的任意两个向量,请发表评论。
  • 看看medley。它包含一个 interleave-all 函数,可以满足您的需求。
  • @FrankC。在我的场景中,我使用partition-all 来拆分序列,将函数应用于奇/偶值并重新组合序列。如果原始序列是偶数,我将有两个相同长度的向量。如果原始向量是奇数,则第一个序列将比第二个长一个成员。
  • 感谢@sloth - 不错的小图书馆。

标签: clojure


【解决方案1】:

第一个缺点,其余的用相反的参数交错。

(cons (first a) (interleave b (rest a)))
;=> (:a :b :c :d :e)

【讨论】:

    【解决方案2】:

    Conj nil to the second, interleave colls get all butlast

    (butlast (interleave a (conj b nil)))
    ;=> (:a :b :c :d :e)
    

    【讨论】:

      【解决方案3】:
      (defn interleave+ [& x] 
        (take (* (count x) (apply max (map count x))) 
          (apply interleave (map cycle x))))
      
      (butlast (interleave+ [:a :c :e] [:b :d]))
      => (:a :b :c :d :e)
      

      【讨论】:

      • 我担心你应该解释/详细说明以避免删除。
      【解决方案4】:

      尝试将此作为惰性序列的练习。我怀疑还有更优雅的方法。

      (defn interleave-all
        "interleaves including remainder of longer seqs."
        [& seqs]
        (if (not-empty (first seqs))
          (cons (first (first seqs)) (lazy-seq (apply interleave-all (filter not-empty (concat (rest seqs) [(rest (first seqs))])))))))
      

      【讨论】:

        【解决方案5】:

        如果您希望将nil 附加到始终具有相同的维度结果,这可能是一种方法:

        (defn interleave-all [& seqs]
          (reduce
           (fn [a i]
             (into a (map #(get % i) seqs)))
           []
           (range (apply max (map count seqs)))))
        

        例如:

        (interleave-all [:a] [:b :c])
        

        输出:

        [:a :b nil :c]
        

        这可以用来转置一个矩阵:

        (defn matrix-transpose [input]
          (partition
           (count input)
           (apply interleave-all input)))
        

        例子:

        (matrix-transpose [[:a] [:b :c]])
        

        输出:

        [[:a :b] [nil :c]]
        

        这可用于不同长度列表的表格输出(但您需要固定尺寸以在列表对某些索引没有值的情况下插入任何内容)。

        【讨论】:

        • 需要更改为 (map #(get (vec %) i) seqs)) 以使其与列表一起使用。
        猜你喜欢
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多