Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 从对象列表中的对象属性进行搜索_List_Python 3.x_Class_Object_Search - Fatal编程技术网

List 从对象列表中的对象属性进行搜索

List 从对象列表中的对象属性进行搜索,list,python-3.x,class,object,search,List,Python 3.x,Class,Object,Search,我已经创建了一个充满类对象的列表。每个对象有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 inform

我已经创建了一个充满类对象的列表。每个对象有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" 
Person是类对象,如果您使用:

for i in list:
没有索引列表,你立即迭代这些人,因此
i
是这里的一个人。因此,您可以使用:

if i.name == name:
而不是:

if list[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!") def搜索词(列表): name=str(输入(“您在搜索谁?请输入姓名”)) 对于列表中的i: 如果i.name==名称: 打印(“我们找到了他/她。这是我们关于他的所有信息”+str(i)) 其他: 打印(“找不到。请检查拼写!”) 此外,您最好在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!") def搜索词(列表): name=str(输入(“您在搜索谁?请输入姓名”)) 名单上的人士: 如果person.name==姓名: 打印(“我们找到了他/她。这是我们关于他的所有信息”+str(个人)) 其他: 打印(“找不到。请检查拼写!”)