首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >‘'str’对象没有属性'n‘

‘'str’对象没有属性'n‘
EN

Stack Overflow用户
提问于 2015-08-23 20:53:00
回答 1查看 6.1K关注 0票数 0

我在python中遇到了一个错误:

init Sel.n= points.n AttributeError:'str‘对象没有属性'n’中,第13行文件“C:\Users\user\Users\2.py”

这个错误意味着什么?我做错了什么导致它?

python代码是:

代码语言:javascript
复制
import math,sys

class Cluster:

    points = []
    elem = int(raw_input("how many points do you want to cluster?"))
    for i in range(0, elem):
        points.append(raw_input("Enter next point :"))
        print points

    def __init__(self, points):
        self.points= points
        self.n = points[0].n 

        for p in points:
            if p.n != self.n: raise Exception("ILLEGAL: MULTISPACE CLUSTER")

    # Return a string representation of this Cluster
    def __repr__(self):
        return str(self.points)


    # Return the single-linkage distance between this and another Cluster
    def getSingleDistance(self, cluster):
        ret = getDistance(self.points[0], cluster.points[0])
        for p in self.points:
            for q in cluster.points:
                distance = getDistance(p, q)
                if distance < ret: ret = distance
        return ret
    # Return the complete-linkage distance between this and another Cluster
    def getCompleteDistance(self, cluster):
        ret = getDistance(self.points[0], cluster.points[0])
        for p in self.points:
            for q in cluster.points:
                distance = getDistance(p, q)
                if distance > ret: ret = distance
        return ret
    # Return the centroid-linkage distance between this and another Cluster

    def fuse(self, cluster):
        # Forbid fusion of Clusters in different spaces
        if self.n != cluster.n: raise Exception("ILLEGAL FUSION")
        points = self.points
        points.extend(cluster.points)
        return Cluster(points) 


# -- Return a distance matrix which captures distances between all Clusters
def makeDistanceMatrix(clusters, linkage):
    ret = dict()
    for i in range(len(clusters)):
        for j in range(len(clusters)):
            if j == i: break
            if linkage == 's':
                ret[(i,j)] = clusters[i].getSingleDistance(clusters[j])
            elif linkage == 'c':
                ret[(i,j)] = clusters[i].getCompleteDistance(clusters[j])
            else: raise Exception("INVALID LINKAGE")
    return ret
# -- Return Clusters of Points formed by agglomerative clustering

def agglo(points, linkage, cutoff):
    # Currently, we only allow single, complete, or average linkage
    if not linkage in [ 's', 'c' ]: raise Exception("INVALID LINKAGE")
    # Create singleton Clusters, one for each Point
    clusters = []
    for p in points: clusters.append(Cluster([p]))
    # Set the min_distance between Clusters to zero
    min_distance = 0
    # Loop until the break statement is made
    while (True):
        # Compute a distance matrix for all Clusters
        distances = makeDistanceMatrix(clusters, linkage)
        # Find the key for the Clusters which are closest together
        min_key = distances.keys()[0]
        min_distance = distances[min_key]
        for key in distances.keys():
            if distances[key] < min_distance:
                min_key = key
                min_distance = distances[key]
        # If the min_distance is bigger than the cutoff, terminate the loop
        # Otherwise, agglomerate the closest clusters
        if min_distance > cutoff or len(clusters) == 1: break
        else:
            c1, c2 = clusters[min_key[0]], clusters[min_key[1]]
            clusters.remove(c1)
            clusters.remove(c2)
            clusters.append(c1.fuse(c2))
    # Return the list of Clusters
    return clusters
# -- Get the Euclidean distance between two Points
def getDistance(a, b):
    # Forbid measurements between Points in different spaces
    if a.n != b.n: raise Exception("ILLEGAL: NON-COMPARABLE POINTS")
    # Euclidean distance between a and b is sqrt(sum((a[i]-b[i])^2) for all i)
    ret = 0.0
    for i in range(a.n):
        ret = ret+pow((a.coords[i]-b.coords[i]), 2)
    return math.sqrt(ret)
# -- Create a random Point in n-dimensional space

# -- Plot Clusters using Tkinter
def plot(clusters):
    root = Tk()
    cp = ClusterPlot(root)
    root.mainLoop()
# -- Main function
def main(args):
    linkage, agglo_cutoff = 's', 150.0
    points = Cluster.points
    # Create num_points random Points in n-dimensional space, print them
    print "\nPOINTS:"
    # Cluster the points using the agglomerative algorithm, print the results
    clusters = agglo( points, linkage, agglo_cutoff)
    print "\nAGGLOMERATIVE\nCLUSTERS:"
    for c in clusters: print "C:", c

if __name__ == "__main__": main(sys.argv)     
EN

回答 1

Stack Overflow用户

发布于 2015-08-23 22:13:48

这可能是因为points是一个列表。因此,当您使用points[0]时,它会调用列表中的第一个项,它应该是一个字符串。例如:

代码语言:javascript
复制
srtings = ['hello']
print strings[0]          #returns hello, which is a string

现在,由于.npoints.n中意味着points是一个函数,它可以包含一个名为n的变量,并且可以在调用points.n时使用。但事实并非如此,这是一份清单。而且,由于列表永远不可能有任何属性,所以只要points.n不是函数(另一次是在函数中没有定义n ),points就会一直引发错误。举个例子,当points.n可以被调用而没有错误时:

代码语言:javascript
复制
def points():
    n = []    #You could get an item out of the list by calling points.n[x]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32171419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档