I have created an array whose values are as follows
size=[9, 41, 1368, 887, 307, 9, 114, 81, 9, 34, 12, 13, 12, 4, 548, 3, 77]
I need to group these values keeping a constant value = 9.
Example output required
Group 1
b=41
c=1368,887,307
Group 2
b=114
c=81
Group 3
b=34
c=12,13,12,4,548,3,77
I have no clue how to achieve this, i have tried out following code.
for i in range(0,len(size)):
if size[i-1]!=9:
if(size[0]-size[i])!=0:
print(size[i])
CodePudding user response:
You'll have to scan the input for those 9
values, and each time you encounter it, start a new list for gathering the other values.
Once you have those sublists, you can iterate those and report on the b
and c
parts of those:
size = [9, 41, 1368, 887, 307, 9, 114, 81, 9, 34,
12, 13, 12, 4, 548, 3, 77]
# Spread data into sub lists, separated by 9-values
result = [[]]
for val in size:
if val == 9:
result.append([]) # Start a new sub list
else:
result[-1].append(val) # Append to last sub list
# Remove empty sublists
result = [lst for lst in result if lst]
# Output in terms of b and c:
for b, *c in result:
print("b=", b)
print("c=", c)