by progval · 1y ago · 0 comments
groups = {}
for row in filtered:
key = (row['species'], row['island'])
if key not in groups:
groups[key] = []
groups[key].append(row['body_mass_g'])
can be rewritten as: groups = collections.defaultdict(list)
for row in filtered:
groups[(row['species'], row['island'])].append(row['body_mass_g'])
and variance = sum((x - mean) ** 2 for x in values) / (n - 1)
std_dev = math.sqrt(variance)
as: std_dev = statistics.stddev(values)It's also funny that one would write their own standard deviation function and include Bessel's correction. Usually if I'm manually re-implementing a standard deviation function it's because I'm afraid the implementors blindly applied the correction without considering whether or not it's actually meaningful for the given analysis. At the very least, the correct name for what's implemented there should really be `sample_std_dev`.
In the first instance, the original code is readable and tells me exactly what's what. In your example, you're sacrificing readability for being clever.
Clear code(even if verbose) is better than being clever.
defaultdict is ubiquitous in modern python, and is far from a complicated concept to grasp.
The difference between the examples is so trivial I'm not really sure why the parent comment felt compelled to complain.
Once you get used to a language's "quirks" (so long as they're considered idiomatic), they no longer feel quirky, and it's usually pretty quick.
That said, I'll change my mind here and agree on using std library, but I'd still have separate 'key' assignment here for more clarity.