2017-01-18 10 views
0

クラスオブジェクトでいっぱいのリストを作成しました。各オブジェクトには5つの属性があります。リスト内のオブジェクト属性からオブジェクトを検索

def searchword(list): 

    name = str(input("Who are you searching for? Please enter name")) 

    for i in list: 
     if list[i].name == name: 
      print("We found him/her. Here is all information we have on him" + str(list[i])) 

     else: 
      print("Could not be found. Check spelling!") 

しかし、私はあなたが使用している場合

if list[i].name == name: 
    TypeError: list indices must be integers, not Person" 

人は、まあ、クラスオブジェクト

答えて

1

で、次のエラーを取得しています:私は、その名前を使用してある特定のオブジェクトを検索する必要が

for i in list: 

あなたインデックスのリストを取得できません、yo u はすぐに人に反復するので、iはここの人です。あなたはこのように使用することができます。

if list[i].name == name: 

またはフルに:

if i.name == name: 

の代わりに

さらに
 
def searchword(list): 

    name = str(input("Who are you searching for? Please enter name")) 

    for i in list: 
     if i.name == name: 
      print("We found him/her. Here is all information we have on him" + str(i)) 

     else: 
      print("Could not be found. Check spelling!") 

方が良いので、より意味的にPythonであなたの変数に名前を付ける:

 
def searchword(list): 

    name = str(input("Who are you searching for? Please enter name")) 

    for person in list: 
     if person.name == name: 
      print("We found him/her. Here is all information we have on him" + str(person)) 

     else: 
      print("Could not be found. Check spelling!") 
関連する問題