'Bool对象没有属性索引'错误

时间:2014-04-03 19:56:28

标签: python function runtime-error

我正在尝试编写解决设施位置问题的代码。我在变量data中创建了一个数据结构。 data是一个包含4个列表的列表。 data[0]是一个长度为128的城市名称列表。其他三个目前无关紧要。还有一个名为nearbyCities(cityname, radius, data)的函数,它采用城市名称,半径和数据,并输出半径内的城市列表。假设提到的所有代码都是正确的,为什么是错误:

  File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 232, in locateFacilities
  File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 162, in served
  File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 131, in nearbyCities
AttributeError: 'bool' object has no attribute 'index'
突然冒出来?

这是所讨论的三个功能。 r是我要服务的城市的半径。前两个是我试图调用的第三个帮手。我认为错误在while循环中。

def served(city, r, data, FalseList): #Helper Function 1
    nearbycity=nearbyCities(city, r, data)
    for everycity in nearbycity:
        dex1=data[0].index(everycity)
        FalseList[dex1]=True
    return FalseList

def CountHowManyCitiesAreInRThatAreNotServed(city, FalseList, r, data): #Helper Function 2
    NBC= nearbyCities(city, r, data)
    notserved=0
    for element in NBC:
        if FalseList[data[0].index(element)] == False:
            notserved= notserved+1 
    return notserved

def locateFacilities(data, r):
    FalseList=[False]*128
    Cities=data[0]
    Radius=[]
    output=[]
    for everycity in Cities:
        Radius.append(len(nearbyCities(everycity, r, data)))
    maxito= max(Radius) #Take Radius and find the city that has the most cities in r radius from it. 
    dex= Radius.index(maxito)    
    firstserver=Cities[dex]
    output.append(firstserver)
    FalseList=served(firstserver, r, data, FalseList)

    while FalseList.count(False) > 0:
        WorkingCityList=[]
        Radius2=[]
        temp=[]
        for everycity in Cities:
            if FalseList[Cities.index(everycity)] == False:
                Radius2.append(CountHowManyCitiesAreInRThatAreNotServed(everycity, FalseList, r, data))
                temp.append(everycity)

        maxito=max(Radius2)
        dex = Radius2.index(maxito)
        serverC= temp[dex]
        output.append(serverC)
        FalseList=served(serverC, r, FalseList, data) 

    output.sort()
    return output

这是其余代码的开始

import re #Import Regular Expressions

def createDataStructure():

    f=open('miles.dat')  #Opens file


    CITY_REG = re.compile(r"([^[]+)\[(\d+),(\d+)\](\d+)") #RegularExpression with a pattern that groups 3 diffrent elements. r" takes a raw string and each thing in parentheses are groups. The first group takes a string until there is actual brackets. The second starts at brackets with two integers sperated by a comma. The third takes an intger. The ending " ends the raw string.  
    CITY_TYPES = (str, int, int, int)  # A conversion factor to change the raw string to the desired types.

    #Initialized lists 
    Cities=[]
    Coordinates=[]
    Populations=[]
    TempD=[]
    FileDistances=[]

    #Loop that reads the file line by line
    line=f.readline()
    while line: 


        match = CITY_REG.match(line) #Takes the compiled pattern and matches it. Returns false of not matched. 
        if match:

            temp= [type(dat) for dat,type in zip(match.groups(), CITY_TYPES)] #Returns the matched string and converts it into the desired format. 

            # Moves the matched lists into individual lists
            Cities.append(temp[0]) 
            Coordinates.append([temp[1],temp[2]])
            Populations.append(temp[3])
            if TempD: #Once the distance line(s) are over and a city line is matched this appends the distances to a distance list.

                FileDistances.append(TempD)
            TempD=[]


        elif not(line.startswith('*')): # Runs if the line isn't commented out with a "*" or a matched line (line that starts with a city). 

            g=line.split()  #This chunck takes a str of numbers and converts it into a list of integers. 

            i=0
            intline=[]
            while i != len(g):
                intline.append(int(g[i]))
                i+=1           
            TempD.extend(intline) 


        line=f.readline() 
    f.close() #End parsing file
    FileDistances.append(TempD) #Appends the last distance line
    FileDistances.insert(0,[]) #For first list


    i=0
    j=1

    while i!= 128: #Loop takes lists of distances and makes them len(128) with corresponding distances

        FileDistances[i].reverse() #Reverses the current distance list to correspond with distance from city listed before.
        FileDistances[i].append(0) #Appends 0 because at this point the city distance is it's self.

        counter=i+1
        while len(FileDistances[i]) != 128: #Loop that appends the other distnaces. 

            FileDistances[i].append(FileDistances[counter][-j])
            counter=counter+1

        j+=1
        i+=1


    cities=[]

    for i in Cities: #Removes the commas. I dont know why we need to get rid of the commas...
        new=i.replace(',','')
        cities.append(new)


    #Final product <3        
    MasterList=[cities, Coordinates, Populations, FileDistances]

    return MasterList

getCoordinates

def getCoordinates(cityname, data): #Basic search function

    INDEX=data[0].index(cityname)

    return data[1][INDEX]

getPopulation

def getPopulation (cityname, data): #Basic search function

    INDEX=data[0].index(cityname)

    return data[2][INDEX]

getDistance的

def getDistance (cityname1, cityname2, data): #Basic search function

    INDEX=data[0].index(cityname1)
    INDEX2=data[0].index(cityname2)

    return data[3][INDEX][INDEX2]

nearbyCities

def nearbyCities(cityname, radius, data):

    Cities=data[0]


    INDEX=Cities.index(cityname)

    workinglist=data[3][INDEX] #Data[3] is the distance list
    IndexList=[]
    index = 0
    while index < len(workinglist): #Goes through the lists and outputs the indexes of cities in radius r
        if workinglist[index] <= radius:
            IndexList.append(index)
        index += 1

    output=[]
    for i in IndexList: #Searches the indexes and appends them to an output list
        output.append(Cities[i])
    output.sort()
    return output

可以在http://mirror.unl.edu/ctan/support/graphbase/miles.dat

找到文件miles.dat

1 个答案:

答案 0 :(得分:1)

好吧,似乎data[0]包含一个布尔值,而不是一个字符串。我在一个空的解释器中尝试了这个,并且能够引发同样的异常。

Interpreter errors

您的data列表格式似乎有误。我们需要看到这一点才能找出真正的问题。