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])
将提供:
^{2}$
此代码从列表中的第一个值开始,并查找该值10%以内的所有后续值。所以在您的例子中,它从4开始,找到所有相似的值。任何不在10%范围内的值都将被添加到新的“集合”中。在
因此,一旦它达到9.0,它就会发现它不匹配,所以它将一个新的结果集添加到results字典中,并使用9.0键。现在当它考虑9.4时,它在4.0列表中找不到匹配项,但是它在9.0列表中找到匹配项。所以它将这个值加到第二个结果集中。在