5 ms·
Not the OP, but the inability to write sorted(enumerate([('a', 1), ('b', 2)]), key=lambda (i, (k, v)): (k, i, v)) in Python 3 drives me nuts. They could fix
by mehrdadn 8y ago
Not the OP, but the inability to write
sorted(enumerate([('a', 1), ('b', 2)]), key=lambda (i, (k, v)): (k, i, v))
in Python 3 drives me nuts. They could fix this. It worked in Python 2.
- fredley 8y agoI love writing python, but the lack of decent map/reduce/etc. (that are really good in Javascript - the other language I mainly write) hurts. Stuff like your example really feels burdensome and inelegant in comparison.
- pxndx 8y agoPython list comprehensions _are_ map/reduce.
- mehrdadn 8y agoI think you mean map/filter.
- pxndx 8y agoYes, thanks for correcting me.
- yxhuvud 8y agoSure, but they compose really bad.
- vanderZwan 8y agoWhy? Just assign to a variable, then do another list comprehension on the next line, no?
- yxhuvud 8y agoAnd that is a pretty sad state of affairs compared to ways that do compose well, like the one in Ruby which you can easily chain.
- icebraining 8y agoYeah, PEP 3113 was quite weak. It didn't even explore alternatives (like fixing the introspection without breaking the syntax).
- msluyter 8y agoSeems that the goal here is to sort via the letters 'a', 'b', etc combined with capturing the original ordering? You could do this, although it's admittedly uglier than your example: In [1]: sorted(enumerate([('b', 1), ('c', 3), ('a', 2)]), key=lambda x: (x[1][0], x[0], x[1][1])) Out[1]: [(2, ('a', 2)), (0, ('b', 1)), (1, ('c', 3))] However, if you're flexible about the ordering of the resulting tuples, this seems clearer and reasonably painless: In [1]: sorted((x, i) for i, x in enumerate([('b', 1), ('c', 3), ('a', 2)])) Out[1]: [(('a', 2), 2), (('b', 1), 0), (('c', 3), 1)] I know that doesn't address your underlying complaint. This is mainly to note that the flexibility of Python tends allow a variety of approaches and that sometimes finding the clearest one takes some effort. ("There should be one obvious way to do it..." often does not hold, IMHO.)
- zb 8y ago> this seems clearer and reasonably painless but gives the wrong answer, as you'll see if you try to sort [('a', 2), ('a', 1)]