繁体   English   中英

关于 Python 空列表的错误。 未绑定本地错误

[英]Error regarding Python empty list. UnboundLocalError

我运行了我的代码,它显示了以下错误。

File "C:/Users/PC/PycharmProjects/untitled/test2.py", line 36, in clustering
min_num = y.index(min(y))
UnboundLocalError: local variable 'y' referenced before assignment

该错误也出现在空列表 'list = []' 中。 以下是我的代码。

 def clustering(self, parsedData=np.genfromtxt("0.txt"), iterCount=0, k=0, centroids=None):
    if centroids is None:  # when no centroids are passed in, randomize the centroids
        np.random.seed(1111)
        centroids = []
        for i in range(k):
            centroids.append(np.random.randint(0, len(parsedData[0])))  # adding centroid numbers from dataset
            new1 = [[] for x in range(len(centroids))]
            y = []
            lis = []
        for i in parsedData[0]:
            for j in centroids:
                x = []
                if i == j:
                    for k in (parsedData.ix[i][2:4]):  # calculating and adding the actual centroids to a list
                        x.append(k)
                    lis.append(x)
        centroids = lis

        iterCount += 1
        for a in range(iterCount):
            if a == 0:
                for i in (parsedData[0]):
                    for j in range(len(centroids)):
                        dist = 0
                        dist += distance(parsedData.ix[i, 2:4],
                                         centroids[j])  # same process except, centroids are not random
                        y.append(dist)
                    min_num = y.index(min(y))
                    new1[min_num].append(int(i))
                    y = []

k0 (默认值)时,您的第一个循环(可以初始化y )永远不会运行。 因此,根据centroids的值,您将尝试调用y.append (访问从未分配过的y )或y.index(min(y)) (同样的问题)。

分析您的代码,弄清楚y代表什么,并在尝试使用它之前确保它具有合理的值。

lis也会出现同样的问题,因为k0也无法分配给lis ,从而使分配centroids = lis从未绑定的lis名称中读取。

这 3 行没有正确缩进:

            new1 = [[] for x in range(len(centroids))]
            y = []
            lis = []

它们在for i in range(k):循环中,但它们不应该存在,因为它们不依赖于i k == 0 ,这些赋值都不会完成,所以后面尝试使用这些变量的代码会出错。

将它们缩进 1 级。

 def clustering(self, parsedData=np.genfromtxt("0.txt"), iterCount=0, k=0, centroids=None):
    if centroids is None:  # when no centroids are passed in, randomize the centroids
        np.random.seed(1111)
        centroids = []
        for i in range(k):
            centroids.append(np.random.randint(0, len(parsedData[0])))  # adding centroid numbers from dataset
        new1 = [[] for x in range(len(centroids))]
        y = []
        lis = []
        ...

我不确定,但我认为该函数的所有其余部分也缩进错误。 if centroids is None:if centroids is None:只有随机填充centroids的代码应该在if centroids is None:

暂无
暂无

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

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