Monday, August 14, 2017

Python Grouping Data Elements (itertools groupby)

#PYTHON GROUPING DATA ELEMENTS (ITERTOOLS GROUPBY)

import itertools

#make a iterator that returns consecutive keys and groups from the iterable 
list_01 = [100, 50, 50, 50, 50, 50, 60, 60, 60, 80, 80, 70, 70, 70, 70, 70, 70]

keys = []
groups = []
sorted_list_01 = sorted(list_01)
for k, g in itertools.groupby(sorted_list_01):
    keys.append(k)
    #make g a list
    groups.append(list(g))
    
print(keys, "==>", groups)

#make dict of key and group

dict_list_01 = dict(zip(keys, groups))
print(dict_list_01)

#another example
list_02 = 'AAAAAAACCCDDEEEEFF'
sorted_list_02 = sorted(list_02)
dict_list_02 = dict(zip([k for k, g in itertools.groupby(sorted_list_02)], 
                        [list(g) for k, g in itertools.groupby(sorted_list_02)]))
print(dict_list_02)

dict_list_02_len = dict(zip([k for k, g in itertools.groupby(sorted_list_02)], 
                            [len(list(g)) for k, g in itertools.groupby(sorted_list_02)]))
print(dict_list_02_len)

No comments:

Post a Comment