我用Python创建了一个类,但无法调用该方法

2024-04-26 17:44:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我要完成的我编写了这段代码,这样我就可以使用统计中的bootstrapping方法来创建95%的平均值置信区间。我想将一个整数列表传递给“CI”方法,然后让该方法在末尾返回字符串。你知道吗

问题-运行代码时,代码不会生成任何输出。请帮帮我!你知道吗

代码如下:

class bootstrapping(object):

    def __init__(self,hours=[]):
        self.hours = hours

    def CI(self,hours):
        from random import randint
        x=0
        for numbers in range(0,1000):
            bootstraplist = []
            while x >= 0:
                bootstraplist.append(hours[randint(0,6)])
            if x <= 5:
                x += 1
                continue
            else:
                break
        listofmeans.append(sum(bootstraplist) / len(bootstraplist))
        import numpy
        s = numpy.std(listofmeans)
        z = 1.96

        lower_confidence = (sum(listofmeans) / len(listofmeans)) - z*s
        upper_confidence = (sum(listofmeans) / len(listofmeans)) + z*s

        return "Lower confidence:",lower_confidence,"Upper confidence:",upper_confidence

Snapshot of the error I'm seeing


Tags: 方法代码importselfcilendefsum
1条回答
网友
1楼 · 发布于 2024-04-26 17:44:05

问题在于:

while x >= 0:
    bootstraplist.append(hours[randint(0,6)])

这是一个无限循环,应该知道缩进级别是在python中创建代码块的原因,因此下面的ifwhile具有相同的级别,if位于while块之外。你知道吗

我不知道你的目标是什么,但是更简单的方法是在一个范围(n)上使用for循环,其中n是重复操作的次数。你的情况可能是这样的

for _ in range(5):
    bootstraplist.append(hours[randint(0,6)])

(使用_是变量的约定,我们不关心它的值和/或不使用它)

或者可以使用列表理解直接创建列表

bootstraplist = [hours[randint(0,6)] for _ in range(5) ]

另外,您使用它的方式看起来好像不是randint,^{}是更好的选择

bootstraplist = [choice(hours) for _ in range(5) ]

另外,将所有导入放在代码中做的第一件事是一种很好的做法。你知道吗

考虑到这一点以及评论,也许这就是你想要的?你知道吗

import numpy
from random import choice

class bootstrapping(object):

    def __init__(self,hours=[]):
        self.hours = hours

    def CI(self):
        listofmeans = []
        for numbers in range(0,1000):
            bootstraplist = [ choice(self.hours) for _ in range(5) ]    
            listofmeans.append(sum(bootstraplist) / len(bootstraplist))

        s = numpy.std(listofmeans)
        z = 1.96

        lower_confidence = (sum(listofmeans) / len(listofmeans)) - z*s
        upper_confidence = (sum(listofmeans) / len(listofmeans)) + z*s

        return "Lower confidence:",lower_confidence,"Upper confidence:",upper_confidence

试验

>>> test=bootstrapping(range(1,6))
>>> test.CI()
('Lower confidence:', 1.7676140938359097, 'Upper confidence:', 4.2427859061640962)
>>>  

相关问题 更多 >