30 seconds of python

  Back to Home



Groups the elements of a list based on the given function and returns the count of elements in each group.

Use map() to map the values of the given list using the given function. Iterate over the map and increase the element count each time it occurs.

def count_by(arr, fn=lambda x: x):
  key = {}
  for el in map(fn, arr):
    key[el] = 1 if el not in key else key[el] + 1
  return key