Skip to content

Instantly share code, notes, and snippets.

@jrheling
Created January 29, 2020 12:56
Show Gist options
  • Save jrheling/6a3b06f3a8ab3347270f24e1ef713c72 to your computer and use it in GitHub Desktop.
Save jrheling/6a3b06f3a8ab3347270f24e1ef713c72 to your computer and use it in GitHub Desktop.
python groupby() equivalent with unsorted immutable input
# goal: use nested list comprehension to do the equivalent of groupby
# but with unsorted input that can't be changed
#
# given input like:
# [('foo', 1), ('bar', 3), ('foo', 4), ('bar', 2)]
#
# produce output like:
# [[('foo', 1), ('foo', 4)], [('bar', 3), ('bar', 2)]]
#
# groupby() can do this, but needs its input sorted. Here's how to do
# it using map/filter instead
input_list = [('foo', 1), ('bar', 3), ('foo', 4), ('bar', 2)]
# get unique list of grouping terms
groupby_items = set(map(lambda x: x[0], input_list))
# generalize that
grouped = [list(filter(lambda x: x[0] == i, input_list)) for i in groupby_items]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment