我有一个很大的数字列表,我想知道它们中的任何一个是否大致相等.如果两个数字“近似相等”(为了我的目的),它们都落在彼此的10%之内(参见下面的两个例子.)然后我想将它们分成大约相等数字的单独列表.
示例#1
比较5.0和5.5:
5.5 / – 10%= 4.95到6.05(5.0在此范围内)
5.0 / – 10%= 4.50到5.50(并且5.5在此范围内)
因此,5.0和5.5大致相等.
例#2
比较5.0和5.6:
5.6 / – 10%= 5.04到6.16(5.0在此范围内)
5.0 / – 10%= 4.50到5.50(5.6不在此范围内)
因此,5.0和5.6并不大致相等.
我需要做的总结:
输入= {4.0,4.1,4.2,4.0,9.0,9.4,8.9,4.3}
期望输出= {4.0,4.1,4.2,4.0,4.3}和{9.0,9.4,8.9}
最佳答案
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])
会给:
results = { 9.0: [9.0, 9.4, 8.9],
4.0: [4.0, 4.1, 4.2, 4.0, 4.3] }
此代码以列表中的第一个值开头,并查找在该列表的10%范围内的所有后续值.因此,在您的示例中,它以4开头,并查找所有类似的值.任何不在10%以内的值都会添加到新的“集合”中.
因此,一旦达到9.0,它就会发现它不匹配,因此它将新的结果集添加到结果字典中,其键为9.0.现在当它考虑9.4时,它在4.0列表中找不到匹配,但它确实在9.0列表中找到匹配.因此它将此值添加到第二个结果集.