Menu

gitpiper

count_by python Code Snippet in 2024

listintermediate

Last Updated: 9 April 2024

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

  • Use collections.defaultdict to initialize a dictionary.
  • 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.
from collections import defaultdict def count_by(lst, fn = lambda x: x): count = defaultdict(int) for val in map(fn, lst): count[val] += 1 return dict(count)
from math import floor count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1} count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}

python snippet similar to count_by For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️