2016-12-23 4 views
0

私のプログラムは、ユーザーからの3つの入力(名前、人口、郡)を受け入れます。これらの詳細は配列になり、次に別の配列に追加されます。ユーザは次に郡名を入力し、対応する町の詳細が提示される。関数searchList内の範囲外のインデックスについてエラーが表示されます。私は答えのためのstackoverflowを見て、何も見つけ出して、私は過去3時間何をすべきかを試してみるのに費やしました。助けてください、私はプログラミングに新しいです。インデックスが範囲外です - searchList関数が機能していません

は、私はまた、numpyのためのソリューションをしてください尋ねることはできません。私はこれがnumpyとの簡単な作業であることを知っていますが、私は外部モジュールをインストールする権限のない仕事用コンピュータです。私はこれが標準的なライブラリで行うことができることを知っている、私はちょうど方法を知らない。

私はあなたがあなたのsearchList機能変更する必要は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

を使用しています:これ

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

、リストを反復処理するとき、あなたが実際にその要素を反復処理、

をあなたのリストの各「記録」を超える
for entry in myList 

反復します。次に、各レコードの3番目の要素である郡を探しているため、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

ありがとう!どのように私は都市名と人口だけの結果を 'town name:population'のような形式で表示できますか? – Arbiter

+0

私は答えを編集しました。 –

+0

はい、私はまた、郡なく更新答えは郡を表示しません – Arbiter

関連する問題