9 ms·
I see your point, but I think your Python's not terribly idiomatic and that's a big part of the problem. This is easier to read and understand, only goes throu
by samdk 16y ago
I see your point, but I think your Python's not terribly idiomatic and that's a big part of the problem.
This is easier to read and understand, only goes through the list twice, and loses nothing in terms of power:
[j*j for j in [i+1 for i in a] if j%3 != 0]
(And for any given operation, there's very possibly a cleaner way to abstract out the inner list comprehension, which would again make it a lot nicer.)
In general, I don't see much of a reason to use filter/map/etc in Python: weak lambdas mean they're not terribly powerful. List/sequence comprehensions can do everything they can do with cleaner syntax and/or fewer operations.
This, I think, is actually at the core of this whole discussion. The Ruby/bash approach makes sense if you're used to working with sequences like Ruby/bash do. The Python approach is more natural to me though, because I've written a lot of Python. (And having spent the last year writing a lot of Ruby, I still find the Python approach cleaner/easier to understand at a glance.)
- LordLandon_ 16y ago[(i+1)**2 for i in a if i%3!=2] Goes through the list once, and reads like set notation! (and does i+1 once, which is what I assume you were going for with the separate [i+1 for i in a])
- samdk 16y agoI kept the i+1 separate because the parent noted that this was a trivial example and wanted to make a point about the more general map-filter-map operation. I wanted to make the point that you can do the map-filter-map in Python more succinctly and more efficiently without sacrificing any power or flexibility. In this example, yes, it's easy to solve the problem with only one iteration through the list. In a more complicated example (especially when the first map step is expensive and you really only want to do it once) this kind of solution may not work.