简体   繁体   English

查找列表中最接近均值的值

[英]Finding a value closest to the mean in a list

I have a homework and it is developing a code that will take 10 numbers from user. 我有一个家庭作业,它正在开发一个代码,将从用户那里获取10个数字。 Then the code should add these numbers to a list. 然后代码应该将这些数字添加到列表中。 It should not add the same number twice. 它不应该两次添加相同的数字。 When 10 numbers are taken it need to calculate mean. 当取10个数字时,需要计算平均值。 Save the lists original form. 保存列表原始表单。 Sort the list descending. 按列表降序排序。 Then it need to delete only one number closest to the mean in the list. 然后,它只需要删除最接近列表中的平均值的一个数字。

Here is my problem: I cant find the closest number to the mean in the list. 这是我的问题:我无法找到列表中最接近均值的数字。

#I tried this:
liste.append(mean)
liste.sort()
if liste[6]-liste[5]>=liste[5]-liste[4]:
 print("Ortalamaya("+str(mean)+") en yakın sayı "+str(liste[6])+" olarak bulunmuştur.")
 liste.remove(liste[6])
 liste.remove(mean)
else:
 print("Ortalamaya("+str(mean)+") en yakın sayı "+str(liste[4])+" olarak bulunmuştur.")
 liste.remove(liste[4])
 liste.remove(mean)

It doesnt work. 它不起作用。 :( :(

What you did is like removing the median, not mean. 你做的就像删除中位数,而不是意思。 To find the number closest to the mean, scan the list again (you don't need to sort it in the first place): 要查找最接近均值的数字,请再次扫描列表(您不需要首先对其进行排序):

diff = []
for i, value in liste:
    diff.append((abs(value-mean), i))
_, i = min(diff)
liste.pop(i)

We use a list diff to store the absolute difference to the mean and the position, then find the min difference and remove that position from the liste . 我们使用列表diff来存储平均值和位置的绝对差值,然后找到最小差值并从liste移除该位置。 After that, you may add the mean to liste and sort it if that's part of your homework. 之后,您可以添加平均值来liste并对其进行排序,如果这是您的家庭作业的一部分。

I found my questions answer today. 我今天发现了我的问题。 Thanks to @adrtam so much. 非常感谢@adrtam。

(I guess I should make coding thing in English. Because I tried to translate it from Turkish to English. o_o) (我想我应该用英语编写代码。因为我试图将它从土耳其语翻译成英语.o_o)

Here is the answer I need; 这是我需要的答案;

import math

diff_list=list()
for num in numlist:
    diff=mean-num
    diff=math.fabs(diff)
    diff_list.append(diff)
print("str(numlist[diff_list.index(min(diff_list))])"+” is found as the closest number to the mean in the number list and deleted.")
numlist.pop(diff_list.index(min(diff_list)))

I created another list to save the absolute mean-number values of the numbers in number list. 我创建了另一个列表来保存数字列表中数字的绝对平均值。 Then find the closest one to mean. 然后找到最接近的意思。 Take its index. 拿它的索引。 Then delete that index from the number list. 然后从数字列表中删除该索引。 Because they are not sorted so their index should be same. 因为它们没有排序所以它们的索引应该相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM