-2

我怎么能修改这段代码:

def SD(numList):
    cntN=len(numList)
    sumN=0
    for i in numList:
        sumN+=i
    avgVal=float(sumN)/float(cntN)
    sumVar=0.0
    for i in range(cntN):
        sumVar+=float((numList[i]-avgVal)**2)
    return ((float(sumVar)/float((cntN-1)))**0.5)

如果 numList 是列表列表并且我想找到每一行的标准偏差,它会起作用吗?任何帮助表示赞赏

4

2 回答 2

3
def SD(numLists):
    def singleSD(numList):
      cntN=len(numList)
      sumN=0
      for i in numList:
          sumN+=i
      avgVal=float(sumN)/float(cntN)
      sumVar=0.0
      for i in range(cntN):
          sumVar+=float((numList[i]-avgVal)**2)
      return ((float(sumVar)/float((cntN-1)))**0.5)
    return [singleSD(l) for l in numLists]
于 2013-07-17T18:52:36.823 回答
2

与其修改代码,不如做一个列表推导更容易:

[SD(nl) for nl in numLists]

此外,您的SD函数可以使用列表推导简化为:

def SD(numList):
    cntN = len(numList)
    avgVal = float(sum(numList))/cntN
    return (sum((i-avgVal)**2 for i in numList)/(cntN-1))**0.5

你也有很多多余Float

于 2013-07-17T19:18:04.557 回答