如何通过python中的属性从对象列表中选择一个对象 [英] how to select an object from a list of objects by its attribute in python

查看:165
本文介绍了如何通过python中的属性从对象列表中选择一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果已经问过这个问题,但我认为我不知道正确的术语来通过Google搜索合适的解决方案.

Apologies if this question has already been asked but I do not think I know the correct terminology to search for an appropriate solution through google.

我想通过对象的属性值从对象列表中选择一个对象,例如:

I would like to select an object from a list of objects by the value of it's attribute, for example:

class Example():
    def __init__(self):
        self.pList = []
    def addPerson(self,name,number):
        self.pList.append(Person(self,name,number))

class Person():
    def __init__(self,name,number):
        self.nom = name
        self.num = number


a = Example()
a.addPerson('dave',123)
a.addPerson('mike',345)

a.pList #.... somehow select dave by giving the value 123

在我的情况下,该号码将始终是唯一的

in my case the number will always be unique

感谢您的帮助

推荐答案

尝试

dave = next(person for person in a.pList if person.num == 123)

for person in a.pList:
    if person.num == 123:
        break
else:
    print "Not found."
dave = person

这篇关于如何通过python中的属性从对象列表中选择一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆