3 ms·
In python land (Django) for the past couple of months and I've been loving it, just thought this was a good excuse to fire up slime. In clojure... (defn ma
by twism 16y ago
In python land (Django) for the past couple of months and I've been loving it, just thought this was a good excuse to fire up slime. In clojure...
(defn map-comprehension [f sequence]
(reduce #(assoc %1 %2 (f %2)) {} sequence))
usage:
user> (map-comprehension count ["one" "two" "three"])
{"three" 5, "two" 3, "one" 3}
- snprbob86 16y agoPre 2.7, you can just give the dict constructor a generator of tuples: >>> dict((s, len(s)) for s in ["one", "two", "three"]) {'three': 5, 'two': 3, 'one': 3}
- calibraxis 16y agoThank you very much! Lack of simple dict-building had been bothering me.
- omaranto 16y agomap-comprehension is a bad name for that function, since it doesn't give you comprehension-like syntax, instead it is just a function that behaves like map but produces a map instead of another sequence. I'd call it map-map.