Hi! I am trying to create a function that grouping the values from the dictionary in a list, by comparing a value with other values in from the list.
Condition: The difference between the first value and second value must be <=50, to be categorized in the same list.
Given input as:
sample_objects = [
{
'id': 0,
'value': 10
},
{
'id': 1,
'value': 20
},
{
'id': 2,
'value': 80
},
{
'id': 3,
'value': 115
},
{
'id': 4,
'value': 130
},
{
'id': 5,
'value':135
},
{
'id': 6,
'value':250
},
{
'id': 7,
'value':280
}
]
The output should be:
sample_objects = [
[
{
'id': 0,
'value': 10
},
{
'id': 1,
'value': 20
}
],
[
{
'id': 2,
'value': 80
},
{
'id': 3,
'value': 115
},
{
'id': 4,
'value': 130
},
],
[
{
'id': 5,
'value':135
}
],
[
{
'id': 6,
'value':250
},
{
'id': 7,
'value':280
}
]
]
My current function:
def layout_processing():
output = []
for y in range(len(sample_objects)):
test=[]
for z in range(y+1, len(sample_objects)):
if abs(sample_objects[y]['value'] - sample_objects[z]['value']) <= 50:
print(z, 'is in the same container with ', y, '\n')
test.append(sample_objects[y]['value'])
test.append(sample_objects[z]['value'])
else:
print(z, 'is not in the same container with ', y, '\n')
output.append(test)
print('Test', output, '\n')
return output
I hope someone can help with this! Thank you.