-
-
Save IndhumathyChelliah/c82b252462bdd3303aeb87b97add6f5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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