[0.21,5.0,9.0,0.19,0.2,0.1856,0.9,0.14,0.189]
0.19
上面的列表重复了最接近的数字0.21、0.2、0.19、0.185、0.189。 0.21、0.2、0.19、0.185、0.189 的平均值 = 0.974/5 = 0.1948
在这种情况下如何提取重复的最近数字?
注意:-我没有任何大约。假设输出数或它可以是什么。
我看到像下面这样的计数器增量逻辑,它适用于 List consists int values.But in my case the numbers are not natural numbers.
def most_frequent(List):
counter = 0
num = List[0]
for i in List:
curr_frequency = List.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
List = [2, 1, 2, 2, 1, 3]
print(most_frequent(List))
2
要找到重复的最近数字,您可以遍历排序列表并检查连续数字之间的差异。如果差异小于某个阈值,则可以将数字添加到一个组中。这是如何实现这一目标的示例:
import numpy as np
def find_repeated_nearest_numbers(numbers, threshold=0.02):
sorted_numbers = sorted(numbers)
groups = []
current_group = [sorted_numbers[0]]
for i in range(1, len(sorted_numbers)):
if abs(sorted_numbers[i] - sorted_numbers[i - 1]) <= threshold:
current_group.append(sorted_numbers[i])
else:
if len(current_group) > 1:
groups.append(current_group)
current_group = [sorted_numbers[i]]
if len(current_group) > 1:
groups.append(current_group)
return groups
input_list = [0.21, 5.0, 9.0, 0.19, 0.2, 0.1856, 0.9, 0.14, 0.189]
nearest_groups = find_repeated_nearest_numbers(input_list)
# Find the group with the largest number of elements
largest_group = max(nearest_groups, key=len)
# Compute the average of the largest group
average = np.mean(largest_group)
print("Largest group:", largest_group)
print("Average:", average)
在此示例中,
find_repeated_nearest_numbers()
函数查找给定阈值(默认为 0.02)内最接近的数字组。它返回一个组列表,其中每个组都包含最接近的数字。然后,我们找到最大的一组并计算其平均值。
这个例子的输出是:
Largest group: [0.1856, 0.189, 0.19, 0.2, 0.21]
Average: 0.19492000000000003
您可以调整阈值以控制数字的接近程度应被视为“重复最近的数字”。