如何检查列表中的实例对象属性是否等于值

tlo*_*ess 0 python

我有从这个类创建的任意数量的对象:

class Person:
    def __init__(self, name, email):
        self.name = name
        self.email = email
Run Code Online (Sandbox Code Playgroud)

我有这些对象的列表:

myList = []
JohnDoe = Person("John Doe", "jdoe@email.com")
BobbyMcfry = Person("Bobby Mcfry", "bmcfry@email.com")
WardWilkens = Person("Ward Wilkens", "wwilkens@email.com")
myList.append(JohnDoe)
myList.append(BobbyMcfry)
myList.append(WardWilkens)
Run Code Online (Sandbox Code Playgroud)

我想检查某人是否存在,如果存在,则返回其属性 - 如果不存在,请说:

x = input("Who to check for? ")
for i in myList:
    if i.name == x:
        print("Name: {0}\nEmail: {1}".format(i.name, i.email))
    else:
        print("{0} is not on the manifest.".format(x))
Run Code Online (Sandbox Code Playgroud)

这种工作,但为myList中的每个人返回一个或另一个 - 我只想要一个返回...

我意识到我需要做某种事情

if val in myList:....
Run Code Online (Sandbox Code Playgroud)

但我很难说如何在没有遍历每个对象的情况下说出"val"应该是什么

And*_*ark 5

使用循环很好,你只需要处理没有匹配的名称的情况,你可以使用break和轻松地做到这一点else:

x = input("Who to check for? ")
for i in myList:
    if i.name == x:
        print("Name: {0}\nEmail: {1}".format(i.name, i.email))
        break
else:
    # this is only run if 'break' was not executed inside of the loop
    print("{0} is not on the manifest.".format(x))
Run Code Online (Sandbox Code Playgroud)

根据您使用列表的内容,您最好使用字典将名称链接到Person对象:

myDict = {}
JohnDoe = Person("John Doe", "jdoe@email.com")
BobbyMcfry = Person("Bobby Mcfry", "bmcfry@email.com")
WardWilkens = Person("Ward Wilkens", "wwilkens@email.com")
for person in [JohnDoe, BobbyMcfry, WardWilkens]:
    myDict[person.name] = person

x = input("Who to check for? ")
person = myDict.get(x)
if person:
    print("Name: {0}\nEmail: {1}".format(person.name, person.email))
else:
    print("{0} is not on the manifest.".format(x))
Run Code Online (Sandbox Code Playgroud)