“布尔对象没有属性索引”错误

0 投票
1 回答
1891 浏览
提问于 2025-04-18 01:14

我正在尝试写一段代码来解决一个设施选址的问题。我在变量 data 中创建了一个数据结构。data 是一个包含四个列表的列表。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

文件 miles.dat 可以在 http://mirror.unl.edu/ctan/support/graphbase/miles.dat 找到。

1 个回答

2

看起来,data[0] 里面存的是一个布尔值,而不是字符串。我在一个空的解释器里试过,结果也出现了同样的错误。

解释器错误

你的 data 列表的格式似乎有问题。我们需要看到这个列表,才能找出真正的问题所在。

撰写回答