说我有一个对象列表。假设该对象具有数据成员名称'。假设我想要获得具有特定值' name'的所有对象的子列表。任何优雅的方式来做到这一点:
class Person(Base):
name = Column(Text)
p1 = Person(name="joe")
p2 = Person(name="jill")
plst = [ p1, p2 ]
name_test = "jill"
found_people = list()
for person in plst:
if person.name == name_test:
found_people.append(person)
寻找一个不那么冗长的优雅解决方案。不确定这个python代码是否编译:)
答案 0 :(得分:2)
您可以使用list comprehension。
class Person(Base):
name = Column(Text)
plist = [Person(name="joe"), Person(name="jill")]
found_people = [person for person in plist if person.name == "jill"]