2016-12-23 37 views
0

我的程序接受来自用户的3个输入:名称,人口和县。这些细节成为一个数组,然后被附加到另一个数组。然后用户输入一个县名,并显示相应的城镇细节。我在我的函数searchList中收到关于索引超出范围的错误。我已经找到了一个答案的stackoverflow,并没有发现,我已经花了过去三个小时试图找出该做什么。请帮助,我是编程新手。索引超出范围 - 我的searchList功能不起作用

我还可以问,没有解决方案的numpy请。我知道这将是一个简单的任务与numpy,但我在工作电脑没有权限安装外部模块。我知道这可以用标准库完成,我只是不知道如何。

我使用Python 3.4

#my code 
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() 
+0

您可以编辑您的问题,包括完整的错误回溯格式化为代码? – pbreach

回答

0

你应该修改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]将其索引为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 
+0

谢谢!我如何以“城镇名称:人口”等格式显示城镇名称和人口结果 – Arbiter

+0

我编辑了答案,是您要求的吗? –

+0

是的,但我也想知道我如何格式化结果,以便它的一个更可接受的字符串表示形式,没有县显示 – Arbiter