You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Clojure嵌套for循环的输出添加迭代索引

为Clojure嵌套迭代输出添加行索引编号

原代码

(def numbers [:one :two :three :four :five])
(def colors  [:green :red :blue :pink :yellow])
(def letters [:A :B :C :D :E])

(for [x numbers
      i colors
      j letters]
    (println (str x " - " i " - " j)))

这段代码通过三层嵌套迭代生成125行输出,现在需要为每行添加对应的迭代索引编号(从1开始)。

解决方案

可以通过map-indexed为每个迭代结果绑定索引,再结合doseq执行打印操作,代码如下:

(def numbers [:one :two :three :four :five])
(def colors  [:green :red :blue :pink :yellow])
(def letters [:A :B :C :D :E])

(doseq [[idx content] (map-indexed vector
                                   (for [x numbers
                                         i colors
                                         j letters]
                                     (str x " - " i " - " j)))]
  (println (str (inc idx) ". " content)))

代码说明

  • 先用for生成所有组合的字符串序列,避免在迭代中直接执行打印副作用
  • map-indexed vector将序列中的每个元素与它的索引(从0开始)配对成向量,格式为[索引值 内容字符串]
  • inc idx把0起始的索引转换为1起始的行号,符合常规阅读习惯
  • doseq遍历带索引的序列并执行打印,相比原代码中的for,doseq更适合处理这类仅需执行副作用的场景

内容的提问来源于stack exchange,提问作者niloofar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:35:32