如何将字符串集连接到一个带有前缀位置的字符串中?
How do I join string set into a single string with positions prepended?
假设我有这个
(def base ["one" "two" "three"])
我想将其转换为:
1. one
2. two
3. three
(又名 1. one \n2. two \n3. three
)
with join
,我不确定我是否可以在加入前添加一个计数器:
(clojure.string/join " \n" base)
=> "one \ntwo \nthree"
和 doseq
或类似的东西,加上一个原子,我确实得到了单独的字符串,但稍后必须连接起来,比如
(def base ["one" "two" "three"])
(def pos (atom 0))
(defn add-pos
[base]
(for [b base]
(do
(swap! pos inc)
(str @pos ". " b))))
(let [pos-base (add-pos base)]
(clojure.string/join " \n" pos-base))
=> "1. one \n2. two \n3. three"
虽然它有效,但我不知道使用带有 for
语句的原子是否是他执行此操作的最佳方式,它看起来不太像 clojure。
请问有更好的方法吗?
这是 keep-indexed 的工作:
user> (keep-indexed #(str (inc %1) ". " %2) ["one" "two" "three"])
("1. one" "2. two" "3. three")
user> (clojure.string/join "\n"
(keep-indexed
#(str (inc %1) ". " %2)
["one" "two" "three"]))
"1. one\n2. two\n3. three"
schaueho 的 keep-indexed 的一个小替代方案是 map-indexed(发现规律?)
(def base ["one" "two" "three"])
(defn numbered-list [s]
(->> s
(map-indexed #(str (inc %1) ". " %2))
(interpose \newline)
(apply str)))
(numbered-list base) ; => "1. one\n2. two\n3. three"
显然是 interleave 的工作。
(->> (interleave (rest (range)) (repeat ". ") base (repeat " \n"))
(apply str))
;-> "1. one \n2. two \n3. three \n"
假设我有这个
(def base ["one" "two" "three"])
我想将其转换为:
1. one
2. two
3. three
(又名 1. one \n2. two \n3. three
)
with join
,我不确定我是否可以在加入前添加一个计数器:
(clojure.string/join " \n" base)
=> "one \ntwo \nthree"
和 doseq
或类似的东西,加上一个原子,我确实得到了单独的字符串,但稍后必须连接起来,比如
(def base ["one" "two" "three"])
(def pos (atom 0))
(defn add-pos
[base]
(for [b base]
(do
(swap! pos inc)
(str @pos ". " b))))
(let [pos-base (add-pos base)]
(clojure.string/join " \n" pos-base))
=> "1. one \n2. two \n3. three"
虽然它有效,但我不知道使用带有 for
语句的原子是否是他执行此操作的最佳方式,它看起来不太像 clojure。
请问有更好的方法吗?
这是 keep-indexed 的工作:
user> (keep-indexed #(str (inc %1) ". " %2) ["one" "two" "three"])
("1. one" "2. two" "3. three")
user> (clojure.string/join "\n"
(keep-indexed
#(str (inc %1) ". " %2)
["one" "two" "three"]))
"1. one\n2. two\n3. three"
schaueho 的 keep-indexed 的一个小替代方案是 map-indexed(发现规律?)
(def base ["one" "two" "three"])
(defn numbered-list [s]
(->> s
(map-indexed #(str (inc %1) ". " %2))
(interpose \newline)
(apply str)))
(numbered-list base) ; => "1. one\n2. two\n3. three"
显然是 interleave 的工作。
(->> (interleave (rest (range)) (repeat ". ") base (repeat " \n"))
(apply str))
;-> "1. one \n2. two \n3. three \n"