我有一个对象列表,需要获取一个属性具有相同值的所有对象以进一步处理它们。我在谷歌上搜索过的所有内容都已经知道我正在寻找的值(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.attrgetter和 itertools.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/