【问题标题】:Alternatives for converting list of nested maps to a map将嵌套地图列表转换为地图的替代方法
【发布时间】:2011-10-29 20:27:00
【问题描述】:

我有以下工作代码将带有嵌套地图(实际上是推文数据)的列表转换为地图:

(defn filter
  "This function returns a map with the user as key, #followers as value"
  [raw-tweets]

  (let [users (map :user raw-tweets)
        names (map :name users)
        followers (map :followers_count users)]
    (zipmap names followers)))

虽然这可以按预期工作,但我想知道在 Clojure 中是否有更惯用的方法来执行此操作。有其他选择吗?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    您所拥有的一切都很好,尽管您可以使用 reduce 来构建地图:

    (定义用户关注者 [原始推文] (减少 #(assoc %1 (:name %2) (:followers_count %2)) {}(地图:用户原始推文)))

    【讨论】:

      【解决方案2】:

      我才刚刚开始学习 clojure,但我认为这种方式可能更惯用一些。无论如何,这是一种替代方案。

      (defn filter
        "This function returns a map with the user as key, #followers as value"
        [raw-tweets]
        (into {} (map #(let [user (:user %)]
                         [(:name user) (:followers_count user)])
                      raw-tweets)))
      

      它使用一个函数映射原始推文,该函数检索每条推文的用户并返回一个向量,其中包含该用户的名称和关注者数量。 into 函数接受两个序列并将第二个序列的每个元素连接到第一个序列上,这会将向量列表转换为映射,然后再从过滤器函数返回。

      【讨论】:

        【解决方案3】:

        我觉得@Daan 的回答很好,但我会在其中加入解构。

        (defn filter-tweets
          "This function returns a map with the user as key, #followers as value"
          [raw-tweets]
          (into {} (map (fn [{{name :name follower-count :followers_count} :user}]
                          [name follower-count])
                        raw-tweets)))
        

        【讨论】:

          【解决方案4】:

          我不喜欢 (map (fn ...)) 模式 - 这真的只是写 for 理解的丑陋方式。我会这样写:

          (into {}
                (for [{:keys [user]} raw-tweets]
                  ((juxt :name :followers_count) user)))
          

          或者这个,对我来说感觉不太自然,但避免为你只会使用一次的值发明名称。

          (into {} (map (comp (juxt :name :followers_count) :user)
                        raw-tweets))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-04-09
            • 1970-01-01
            • 1970-01-01
            • 2020-07-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多