searchList函数索引超出范围错误

扎克

我的程序接受用户的3个输入:姓名,人口和县。这些细节成为一个数组,然后附加到另一个数组。然后,用户输入县名,并显示相应的城镇详细信息。

我收到有关关于索引超出函数范围的错误searchList

def cathedralTowns():
    def searchList(myCounty, myList): #search function (doesn't work)
        index = 0
        for i in myList:
            myList[index].index(myCounty)
            index += 1
            if myList[index] == myCounty:
                print(myList[index])
    records = [] #main array
    end = False
    while end != True:
        print("\nEnter the details of an English cathedral town.")
        option = input("Type 'Y' to enter details or type 'N' to end: ")
        if option == 'Y':
            name = input("Enter the name of the town: ")
            population = int(input("Enter the population of the town: "))
            county = input("Enter the county the town is in: ")
            records.append([name, population, county]) #smaller array of details of one town
        elif option == 'N':
            print("Input terminated.")
            end = True
        else:
            print("Invalid input. Please try again.")
    print(records) #just for checking what is currently in records array
    end = False
    while end != True:
        print("\nEnter the name of an English county.")
        option = input("Type 'Y' to enter county name or type 'N' to end: ")
        if option == 'Y':
            searchForCounty = input("Enter the name of a county: ")
            searchList(searchForCounty, records) #searchList function takes over from here
        elif option == 'N':
            print("Input terminated.")
            end = True
        else:
            print("Invalid input. Please try again.") 

cathedralTowns()
何塞·桑切斯(Jose Sanchez)

您应该修改您的searchList功能:

def searchList(myCounty, myList):
   for entry in myList:
       if entry[2] == myCounty:
           print("Town: {}, population: {}".format(entry[0], entry[1]))

在Python中,当您迭代列表时,实际上是遍历列表元素,因此

for entry in myList

遍历列表中的每个“记录”。然后,由于您要寻找一个县,即您在每个记录中的第三个元素,entry[2]将其编入索引以将其与查询(即)进行比较myCounty

对于示例记录中的输入示例,例如:

records = [['Canterbury', 45055, 'Kent'], ['Rochester', 27125, 'Kent'], ['Other', 3000, 'Not Kent']]

输出为

searchList('Kent', records)

是:

>>> Town: Canterbury, population: 45055
>>> Town: Rochester, population: 27125

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章