我有从这个类创建的任意数量的对象:
class Person:
def __init__(self, name, email):
self.name = name
self.email = email
我有这些对象的列表:
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)
我想检查某人是否存在,如果存在,则返回他们的属性 - 如果不存在,请说明:
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))
这种作品,但为myList中的每个人返回一个或另一个 - 我只想要一个回复......
我意识到我需要做某种
if val in myList:....
但我很难说如何在没有遍历每个对象的情况下说出“val”应该是什么
答案 0 :(得分: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))
根据您使用列表的内容,您最好使用字典将名称链接到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))
答案 1 :(得分:1)
可以使用itertools
。
try:
found_person = itertools.dropwhile(lambda person: person.name != search_name, people).next()
except StopIteration:
found_person = None