Python获取列表中具有匹配属性的对象

标签 python list attributes generator

我有一个对象列表,需要获取一个属性具有相同值的所有对象以进一步处理它们。我在谷歌上搜索过的所有内容都已经知道我正在寻找的值(value)。相反,我只需要火柴。说我有这个

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("mike", 28)
p2 = Person("joe", 28)
p3 = Person("nick", 27)
p4 = Person("Janet", 27)
people = [p1, p2, p3]
#need something like
matches = getMatches(people, "age")
print matches
[[Mike's object, Joe' Object], [Nick's object, Janet's object]]

我想出了这个并且它有效,但对我来说似乎有点蹩脚

def getMatches(objs, attr):
    def Gen(objs, attr):
        used = [] #already searched for these...
        for obj in objs:
            a = getattr(obj, attr)
            if a not in used:
                yield [p for p in objs if getattr(p, attr) == a]
            used.append(a)
    gen = Gen(objs, attr)
    return [g for g in gen]

在我的实际代码中,需要这个更有意义。谁能帮我清理一下,或者是否有我不知道的标准功能或方法来完成它?

我很欣赏这些答案,最终使用了 groupby 并确保首先对它们进行排序。这是我第一次尝试编写生成器。如果我可能会问,可以这么说,是什么让我的代码正确且符合 Pythonic?

最佳答案

您可以使用 operator.attrgetteritertools.groupby像这样

from operator import attrgetter
from itertools import groupby
def getMatches(people, prop):
    people = sorted(people, key = attrgetter(prop))
    return [list(grp) for k, grp in groupby(people, attrgetter(prop))]

print getMatches(people, "age")

你可以这样查看结果

for group in getMatches(people, "age"):
    print [people.name for people in group]

输出

['mike', 'joe']
['nick', 'Janet']

关于Python获取列表中具有匹配属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557277/

相关文章:

python - 我在 python 中的乘法不起作用

python - pyqt5选项卡区域未填充整个可用空间

list - 如何从自动模式列表中删除项目(Emacs)

C# 允许派生类的多个属性

php - 在文本输入的值属性中使用 htmlspecialchars

python - (不再求答案)Python input box inside a message box

python - 如何使用 pop 函数删除二维数组中的所有元素

list - 跟踪序言代码

python - 使用 for-each 循环、函数定义和 if-else-elif 语句调用列表中的特定元素

c++ - GCC 忽略重写成员函数上的 nodiscard 属性是否正确?