gpt4 book ai didi

Clojure 将映射向量转换为向量值映射

转载 作者:行者123 更新时间:2023-12-02 13:32:21 26 4
gpt4 key购买 nike

有一些与此主题相关的帖子,但是我找不到任何适合我想要完成的任务。

我有一个 map 矢量。我将使用另一个相关 SO 帖子中的示例:

(def data
[{:id 1 :first-name "John1" :last-name "Dow1" :age "14"}
{:id 2 :first-name "John2" :last-name "Dow2" :age "54"}
{:id 3 :first-name "John3" :last-name "Dow3" :age "34"}
{:id 4 :first-name "John4" :last-name "Dow4" :age "12"}
{:id 5 :first-name "John5" :last-name "Dow5" :age "24"}]))

我想将其转换为一个映射,其中每个条目的值是关联值的向量(保持数据的顺序)。

这是我想要的输出:

{:id [1 2 3 4 5]
:first-name ["John1" "John2" "John3" "John4" "John5"]
:last-name ["Dow1" "Dow2" "Dow3" "Dow4" "Dow5"]
:age ["14" "54" "34" "12" "24"]}

在 Clojure 中是否有一种优雅且有效的方法来做到这一点?

最佳答案

可以提高效率,但这是一个很好的开始:

(def ks (keys (first data)))
(zipmap ks (apply map vector (map (apply juxt ks) data))) ;;=>

{:id [1 2 3 4 5]
:first-name ["John1" "John2" "John3" "John4" "John5"]
:last-name ["Dow1" "Dow2" "Dow3" "Dow4" "Dow5"]
:age ["14" "54" "34" "12" "24"]}

另一个接近的:

(group-by key (into [] cat data))

;;=>
{:id [[:id 1] [:id 2] [:id 3] [:id 4] [:id 5]],
:first-name [[:first-name "John1"] [:first-name "John2"] [:first-name "John3"] [:first-name "John4"] [:first-name "John5"]],
:last-name [[:last-name "Dow1"] [:last-name "Dow2"] [:last-name "Dow3"] [:last-name "Dow4"] [:last-name "Dow5"]],
:age [[:age "14"] [:age "54"] [:age "34"] [:age "12"] [:age "24"]]}

关于Clojure 将映射向量转换为向量值映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54367465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com