【问题标题】:Transformation of nested lists into a list of sets in Clojure?将嵌套列表转换为 Clojure 中的集合列表?
【发布时间】:2011-03-14 20:26:20
【问题描述】:

拥有一个大小相同的列表,例如:

(def d [["A" "B"] ["A" "C"] ["H" "M"]])

如何将其转化为一个集合列表,每个集合为上面的索引:

[#{"A" "H"} #{"B" "C" "M"}]

【问题讨论】:

    标签: clojure


    【解决方案1】:
    (map set (apply map vector d))
    

    (apply map vector)”在 Python 等其他语言中就是所谓的“zip”。它在d 的每个元素的第一项上调用vector,然后是每个元素的第二项,依此类推。

    然后我们在每个集合上调用set

    【讨论】:

    • 不错 - +1 非常简洁的解决方案!
    【解决方案2】:

    如果哈希集允许重复键,您可以使用:

    (apply map hash-set d)
    

    相反,你可以做得更丑

    (apply map (fn [& s] (set s)) d)
    

    【讨论】:

      【解决方案3】:

      我建议如下:

      (reduce
        (fn [sets vals]
          (map conj sets vals))
        (map hash-set (first d))
        (rest d))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-12
        • 2011-09-30
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多