Skip to content

Instantly share code, notes, and snippets.

@cgopalan
Last active January 28, 2016 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgopalan/7cd91dac37768ce8edaa to your computer and use it in GitHub Desktop.
Save cgopalan/7cd91dac37768ce8edaa to your computer and use it in GitHub Desktop.
from itertools import groupby
from operator import itemgetter
myvals = [('hello', 'arrival'), ('hi', 'arrival'), ('test', 'no'), ('voo', 'yes'), ('cool', 'arrival')]
[(a,map(itemgetter(1), b))
for a,b in groupby( # 4. Group by key for which you have create list.
sorted([(x, # 3. Sort the keys like arrival, yes, etc.
reduce(lambda a,b: a+' '+b, map(itemgetter(0), y))) # 2. Concantenate the strs with same contiguous key.
for x,y in groupby(myvals, key=lambda e: e[1])]), # 1. Group by key for which you have to concat str.
lambda e: e[0])]
# Output:
# [('arrival', ['cool', 'hello hi']), ('no', ['test']), ('yes', ['voo'])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment