Skip to main content
 首页 » 编程设计

python之开始 Python 打印出标准偏差

2025年05月04日17Leo_wl

我想弄清楚我的代码有什么问题。谁能修好?

def main(): 
   fname = input("Enter filename:") 
   infile = open(fname, "r") 
   SD() 
 
def SD(): 
  b= [] 
  a = 5.0  
  r = len(b)  
  for n in range(r-1): 
      b.append((r[n] -a)**2) 
  m = (float(b)/r)**0.5 
  print("The standard deviation is", m) 
main() 

请您参考如下方法:

你有一些错误:

def SD(): 
 
  # b is empty 
  b= [] 
  a = 5.0  
 
  #this will always be 0 
  r = len(b)  
 
  # range(r-1) == [] because it is range(-1) 
  # whole loop is skipped 
  for n in range(r-1): 
      b.append((r[n] -a)**2) 
 
  # float(b) should throw an error, maybe sum(b) ? 
  m = (float(b)/r)**0.5 
  print("The standard deviation is", m) 
main() 

b 是一个列表;您不能将列表转换为 float 。

也许您想将数组传递给 SD()?您应该 read() 文件内容,然后可能 split() 将其放入数组并将其作为参数传递给 SD()(您将调用 int() 在他们身上。)