Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created Jul 7, 2020
Embed
What would you like to do?
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