Skip to content

Home

Count grouped elements

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

from collections import defaultdict
from math import floor

def count_by(lst, fn = lambda x: x):
  count = defaultdict(int)
  for val in map(fn, lst):
    count[val] += 1
  return dict(count)

count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}

More like this

Start typing a keyphrase to see matching snippets.