Skip to content

Instantly share code, notes, and snippets.

@alanyee
Last active January 22, 2020 22:25
Show Gist options
  • Save alanyee/ed8849a5cd4c7b76525b38b2dcbe3b68 to your computer and use it in GitHub Desktop.
Save alanyee/ed8849a5cd4c7b76525b38b2dcbe3b68 to your computer and use it in GitHub Desktop.
from functools import partial
def iseven(n, d=2):
"""Example"""
return n % d == 0
def groupby(key, seq):
"""Based on toolz groupby"""
result = defaultdict(list)
for item in seq:
result[key(item)].append(item)
return result
array = [1, 2, 3, 4, 5, 6, 7, 8]
groupby(iseven, array) # {False: [1, 3, 5, 7], True: [2, 4, 6, 8]}
groupby(partial(iseven, d=1), array) # {True: [1, 2, 3, 4, 5, 6, 7, 8]}
groupby(partial(iseven, d=3), array) # {False: [1, 2, 4, 5, 7, 8], True: [3, 6]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment