Skip to content

Instantly share code, notes, and snippets.

@hsleonis
Last active May 25, 2020 22:14
Show Gist options
  • Save hsleonis/1df84cbfab489a13756dde55ff6be011 to your computer and use it in GitHub Desktop.
Save hsleonis/1df84cbfab489a13756dde55ff6be011 to your computer and use it in GitHub Desktop.
Returns the average of a list, after mapping each element to a value using the provided function.
def mean_by(lst, f=lambda el: el):
  return sum(map(f, lst), 0.0) / len(lst)
mean_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda p: p['n']) # 5.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment