python - 如何通过python中的属性从对象列表中选择一个对象

标签 python oop

如果这个问题已经被问到,我深表歉意,但我认为我不知道通过谷歌搜索合适解决方案的正确术语。

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

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

在我的例子中,数字将始终是唯一的

感谢帮助

最佳答案

一种选择是使用内置的next():

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

如果没有找到,这将抛出 StopIteration。您可以使用 next() 的双参数形式为该情况提供默认值:

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

一个稍微冗长的替代方案是 for 循环:

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

关于python - 如何通过python中的属性从对象列表中选择一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5180092/

相关文章:

java - 使用父类(super class)引用调用重载的继承方法

javascript - 如何创建一个扩展未预先确定的其他类的类

C++ 从事件处理程序中获取数据并传递给另一个类的方法?

oop - 什么是对象遮挡?

python - 使用 Python 查找网络(外部)IP 地址

python - Pygame 碰撞不起作用

python - python脚本的shell启动/停止

python - 在 Python 中对不同类别的 n 长度数组中的分类数据进行编码

python - 使用 Cython 进行扩展,名称与源文件不同

oop - Nim 中的无根据方法是什么?