4 ms·
Because this is turning into a fun language code-off, here's something in Python: ', '.join(sorted(str(x) for x in set(map1) | set(map2))) or '<none>' Thi
by pjscott 14y ago
Because this is turning into a fun language code-off, here's something in Python:
', '.join(sorted(str(x) for x in set(map1) | set(map2))) or '<none>'
This works by making sets of the keys of map1 and map2, taking the union of those sets, converting each key to a string, sorting those strings, and joining them with ', '. And then if that generated an empty string -- if both dicts were empty -- then it evaluates to '<none>'.
Am I missing some difficulty here?
EDIT: and for an arbitrary number of maps, this one works:
import itertools
', '.join(sorted({str(x) for x in itertools.chain(*maps)})) or '<none>'
It iterates over all the keys of all the maps with itertools.chain(), converts everything to a string, adds everything to a set, sorts them, and then joins them with commas. I realize it's not a one-liner anymore because of the itertools import, but it's still pretty simple to follow.
I like Clojure, but for problems like this, it just doesn't seem to be doing quite as well as languages like Python.
- jshen 14y agoI've never liked python code like this because I can't read it in left-to-right order nor right-to-left order. You have to read into the comprehension, then read left, then finally jump far right to the 'or'
- cgag 14y agoIt depends how you define better I suppose. I think they're both very readable, but I'm very willing to give up a little terseness for the benefits of a simpler syntax, immutable datastructures, and the kind of flexibility that lets you write things like -> to invert your control flow.