如何将字符串列表转换为闭包中的双精度列表?

时间:2012-12-14 02:39:53

标签: clojure

如何在创建mymap的同时将'mymap'的值转换为双打列表而不是字符串列表?

(use '[clojure.string :only (join split)])
;(def raw-data (slurp "http://ichart.finance.yahoo.com/table.csv?s=INTC"))
;Downloaded and removed the first line
(def raw-data (slurp "table-INTC.csv"))


(def raw-vector-list
  (map
    #(split % #",")          ; anonymous map function to split by comma
    (split raw-data #"\n"))) ; split raw data by new line

(pr (take 1 raw-vector-list))

(def mymap 
  (zipmap 

    ;construct composite key out of symbol and date which is head of the list
    (map #(str "INTC-" %) (map first raw-vector-list))

    ;How do i convert these values to Double instead of Strings?
    (map rest raw-vector-list)))

(pr (take 1 mymap))     

2 个答案:

答案 0 :(得分:0)

(def mymap
  (zipmap 
    (map #(str "NAT-" %) (map first raw-vector-list)) 
    (map #(map (fn [v] (Double/parseDouble v)) %)
         (map rest raw-vector-list))))

(pprint (take 1 mymap))
-> (["NAT-1991-09-30" (41.75 42.25 41.25 42.25 3.62112E7 1.03)])

另一个版本

(def mymap
  (map (fn [[date & values]]
         [(str "NAT-" date)
          (map #(Double/parseDouble %) values)])
       ;; Drop first non-parsable element in raw-vector-list
       ;; ["Date" "Open" "High" "Low" "Close" "Volume" "Adj Close"]
       (drop 1 raw-vector-list)))

答案 1 :(得分:0)

因此对于此数据的尾部/休息部分。您正在将匿名的map函数映射到字符串列表,然后将类型转换映射到每个子列表中的元素。

(def mymap
  (zipmap 
   (map #(str "NAT-" %) (map first raw-vector-list)) 
   (map #(map (fn [v] (Double/parseDouble v)) %)
     (map rest raw-vector-list))))

如何将类型转换转换为如下函数...然后使用我的自定义方法?

(defn str-to-dbl [n] (Double/parseDouble n))

此代码抱怨嵌套的#。

(def mymap
  (zipmap 
   (map #(str "NAT-" %) (map first raw-vector-list)) 
   (map #(map #(str-to-double %)
     (map rest raw-vector-list))))