简体   繁体   English

如何在Clojure中将哈希图列表转换为一个hasmap?

[英]How to convert list of hashmaps into one hasmap in clojure?

I have a list which looks like this: 我有一个看起来像这样的清单:

({:course 2, :mark 9} {:course 5, :mark 8} {:course 6, :mark 10})

And i want to convert it to hashmap: 我想将其转换为hashmap:

{:2 9 :5 8 :6 10}

List was created from mysql database, i dont know can i get that datas from database in some other format, which will be easier to convert to one hashmap, i used java.jdbc query function. 列表是从mysql数据库创建的,我不知道我能以其他某种格式从数据库中获取数据,这将更易于转换为一个哈希图,我使用了java.jdbc查询功能。

Can anybody help me? 有谁能够帮助我?

(fn [data] (into {} (map (juxt :course :mark) data)))

on

(list {:course 2, :mark 9} {:course 5, :mark 8} {:course 6, :mark 10})

produces 产生

{2 9, 5 8, 6 10}

The keyword function does not accept numbers as arguments, so I don't think you can get quite what you were looking for. keyword函数不接受数字作为参数,因此我认为您无法获得想要的东西。 But digits are as good keys as keywords anyway. 但是无论如何,数字和关键字一样是很好的关键字。


Wrong! 错误! As others have demonstrated, Clojure accepts digit strings as keywords. 正如其他人所展示的那样,Clojure接受数字字符串作为关键字。 We can adapt the above to use such: 我们可以将上述内容改编成这样:

(fn [data] (into {} (map (juxt (comp keyword str :course) :mark) data)))

on

(list {:course 2, :mark 9} {:course 5, :mark 8} {:course 6, :mark 10})

produces 产生

{:2 9, :5 8, :6 10}

But, as I've said, I think this is needlessly risky. 但是,正如我所说,我认为这是不必要的冒险。 Why not just use the numbers as keys? 为什么不只将数字用作键?


Further to using digit (strings) as keywords: 除了使用数字(字符串)作为关键字之外:

The reader doc about symbols says 读者关于符号的文档

  • Symbols begin with a non-numeric character ... 符号以非数字字符开头...
  • Keywords are like symbols, except: ... (further restricted) 关键字与符号类似,不同之处在于:...(进一步限制)

Another variant. 另一个变体。 (Probably less efficient than Thumbnail's if you've got a lot of data.) (如果您有很多数据,效率可能会比Thumbnail低。)

(zipmap (map (comp keyword str :course)  data)
        (map :mark data))

where data is in the format specified in the question. data采用问题中指定的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM