【发布时间】:2017-11-13 04:05:17
【问题描述】:
clojure 新手。尝试用java背景解决以下问题。我需要将表转换为将产品映射到销售该产品的所有城市的哈希图。所以输出应该是。
{"Pencil": ("Oshawa" "Toronto")
"Bread": ("Ottawa" "Oshawa" "Toronto")}
(def table [
{:product "Pencil"
:city "Toronto"
:year "2010"
:sales "2653.00"}
{:product "Pencil"
:city "Oshawa"
:year "2010"
:sales "525.00"}
{:product "Bread"
:city "Toronto"
:year "2010"
:sales "136,264.00"}
{:product "Bread"
:city "Oshawa"
:year "nil"
:sales "242,634.00"}
{:product "Bread"
:city "Ottawa"
:year "2011"
:sales "426,164.00"}])
这是我目前所拥有的。我将此代码写入repl。
(let [product-cities {}]
(for [row table]
(if (= (contains? product-cities (keyword (row :product))) true)
(println "YAMON") ;;To do after. Add city to product if statement is true
(into product-cities {(keyword (row :product)) (str (row :city))}))))
但是,结果如下:
({:Pencil "Toronto"}
{:Pencil "Oshawa"}
{:Bread "Toronto"}
{:Bread "Oshawa"}
{:Bread "Ottawa"})
我的 if 语句一直返回 false。我看到许多哈希映射周围都有半圆括号。我不明白为什么它没有返回一个哈希图以及为什么有很多哈希图?谢谢
编辑:
问题 2: 将表转换为将产品映射到销售额最高的城市的哈希图。例如,输出应如下所示:
{"Pencil": "Toronto"
"Bread": "Ottawa"}
我认为需要一种不同于建立价值的策略,但我的想法如下:
(reduce (fn [product-cities {:keys [product city sales]}]
(update-in product-cities [product] (fnil conj []) {(keyword city) sales}))
{}
table)
这会产生以下输出:
{"Bread"
[{:Toronto "136,264.00"}
{:Oshawa "242,634.00"}
{:Ottawa "426,164.00"}],
"Pencil"
[{:Toronto "2653.00"}
{:Oshawa "525.00"}]}
然后我可以再次使用 reduce 函数,但只添加销售额最高的城市。我认为这不是最有效的方法。
【问题讨论】:
标签: clojure