Processing pairs of values from two sequences in Clojure

江枫思渺然 提交于 2020-01-12 05:22:13

问题


I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?


回答1:


Another way is to simply use map together with some function that collects its arguments in a sequence, like this:

user=> (map vector '(1 2 3) "abc")
([1 \a] [2 \b] [3 \c])



回答2:


(zipmap [:a :b :c] (range 3))
-> {:c 2, :b 1, :a 0}

Iterating over maps happens pairwise, e.g. like this:

(doseq [[k v] (zipmap [:a :b :c] (range 3))]
  (printf "key: %s, value: %s\n" k v))

prints:

key: :c, value: 2
key: :b, value: 1
key: :a, value: 0



回答3:


The question has been answered, but there's still interleave, which also handles an arbitrary number of sequences, but does not group the resulting sequence into tuples (but you can use partition for that).



来源:https://stackoverflow.com/questions/1009037/processing-pairs-of-values-from-two-sequences-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!