input_list = [4.0, 4.1, 4.2, 4.0, 9.0, 9.4, 8.9, 4.3]
results = {input_list[0]: [input_list[0]]} # Start with first value
for value in input_list[1:]: # loop through our entire list after first value
hi = value * 1.1
low = value * 0.9
print("Value: {0}\tHi: {1}\tLow:{2}".format(value, hi, low))
for existing in results: # search through our result set
found_similar = False
if low < existing < hi: # if we find a match
results[existing].append(value) # we add our value to the list for that set
found_similar = True
break
if not found_similar: # if we looped through our entire results without a match
results[value] = [value] # Create a new entry in our results dictionary
for entry in results:
print(results[entry])
Will give:
results = { 9.0: [9.0, 9.4, 8.9],
4.0: [4.0, 4.1, 4.2, 4.0, 4.3] }
This code starts with the first value in your list, and finds all subsequent values that are within 10% of that one. So in your example, it starts with 4, and finds all similar values. Any value that isn't within 10 % get added to a new "set".
So once it reaches 9.0, it sees that it's not a match, so it adds a new result set to the results
dictionary, with a key of 9.0
. Now when it considers 9.4, it doesn't find a match in the 4.0 list, but it does find a match in the 9.0 list. So it adds this value to the second result set.