Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created July 7, 2020 03:50
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 IndhumathyChelliah/c82b252462bdd3303aeb87b97add6f5b to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/c82b252462bdd3303aeb87b97add6f5b to your computer and use it in GitHub Desktop.
import itertools
l1=[('color','red'),('color','blue'),('color','green'),('Numbers',1),('Numbers',5)]
l2=itertools.groupby(l1,key=lambda x:x[0])
print (l2)#Output:<itertools.groupby object at 0x0305F528>
for key,group in l2:
result={key:list(group)}
print (result)
'''
Output:
{'color': [('color', 'red'), ('color', 'blue'), ('color', 'green')]}
{'Numbers': [('Numbers', 1), ('Numbers', 5)]}
'''
#list doesn't contain sorted data based on the key function.It breaks the group every time,when value of key function changes.
l1=[('color','red'),('color','blue'),('color','green'),('Numbers',1),('Numbers',5),('color','purple')]
l2=itertools.groupby(l1,key=lambda x:x[0])
print (l2)#Output:<itertools.groupby object at 0x028AF5A0>
for key,group in l2:
result={key:list(group)}
print (result)
'''
Output:
{'color': [('color', 'red'), ('color', 'blue'), ('color', 'green')]}
{'Numbers': [('Numbers', 1), ('Numbers', 5)]}
{'color': [('color', 'purple')]}
'''
#key is not mentioned
l1=[('color','red'),('color','blue'),('color','green'),('Numbers',1),('Numbers',5),('color','purple')]
l2=itertools.groupby(l1)
print (l2)#Output:<itertools.groupby object at 0x028AF578>
for key,group in l2:
result={key:list(group)}
print (result)
'''
Output:
{('color', 'red'): [('color', 'red')]}
{('color', 'blue'): [('color', 'blue')]}
{('color', 'green'): [('color', 'green')]}
{('Numbers', 1): [('Numbers', 1)]}
{('Numbers', 5): [('Numbers', 5)]}
{('color', 'purple'): [('color', 'purple')]}
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment