import itertools
data1 =[100,80,80,80,80,80,90,90,85,85,85]
keys = []
groups = []
sorted_data1 = sorted(data1)
for k,g in itertools.groupby(sorted_data1):
#print('key: ',k,' group: ',list(g))
keys.append(k)
groups.append(list(g))
print('keys: ', keys)
print('Groups: ', groups)
RESULT OF ABOVE CODE:
keys: [80, 85, 90, 100]
Groups: [[80, 80, 80, 80, 80], [85, 85, 85], [90, 90], [100]]
RESULT I GET WHEN 'print()' IS UNCOMMENTED:
key: 80 group: [80, 80, 80, 80, 80]
key: 85 group: [85, 85, 85]
key: 90 group: [90, 90]
key: 100 group: [100]
keys: [80, 85, 90, 100]
Groups: [[], [], [], []]
Un-commenting print() in for-loop is giving 'groups' as list of empty lists. Please look into it.
In the loop
for k,g in itertools.groupby(sorted_data1):
g is itself an iterator, it's not a collection like a list.
When you call
print('key: ',k,' group: ',list(g))
inside the loop, the list(g) inside the print already goes through the entire iterator g to create the list. So, when you call
groups.append(list(g))
afterwards, g is already "empty" in some sense (more precisely: it is pointing to the end of the iterator), so there's nothing left to put in the list anymore
Like DDGG suggested, you can store the results of iterating through g once in a more permanent collection (like a list) first. Then you can re-use that list multiple times
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With