gpt4 book ai didi

for-loop - Clojure,增加一个计数器

转载 作者:行者123 更新时间:2023-12-01 22:04:11 24 4
gpt4 key购买 nike

我有一个如下所示的集合:

[({:customer_id "111", :product_id "222"})({:customer_id "333", :product_id "444"}{:customer_id "555", :product_id "666"})...]

我想标记集合中哈希的“位置”。最后我希望我的哈希看起来像这样:

[({:product_id "222", :number "1"})({:product_id "444", :number "1"}{:product_id "666", :number "2"})...]

我尝试过这样的:

(->> (pig/load-clj "resources/test0_file")
(pig/map
(fn [ord]
(for [{:keys [product_id]} ord]
(let [nb (swap! (atom 0) inc)]
{:product_id product_id :number nb}))))

但在这种情况下 nb 不会增加。谢谢你的帮助

最佳答案

map-indexed、assoc 和 dissoc 提供了更简洁的解决方案

(def products ['({:customer_id "111", :product_id "222"})
'({:customer_id "333", :product_id "444"}
{:customer_id "555", :product_id "666"})])


(for [p products]
(map-indexed #(dissoc (assoc %2 :number (str (inc %))) :customer_id ) p))
;user=>(({:number 1, :product_id "222"}) ({:number 1, :product_id "444"} {:number 2, :product_id "666"}))

关于for-loop - Clojure,增加一个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798831/

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