如何在对象列表中搜索属性?假设我想要所有对象的fname以及年龄> 30或找到一些匹配
#!usr/bin/python
import sys
import pickle
class People:
def __init__(self, fname=None, lname=None, age=None, gender=None):
self.fname = fname
self.lname = lname
self.age = age
self.gender = gender
def display(self):
#fp = open("abc","w")
#fp.write("F.Name: "+ppl.fname+ "\nLName: "+ ppl.lname + "\nAge: "+ str(ppl.age)+ "\nGender: "+ ppl.gender)
ppl = [People("Bean", "Sparrow", 22, "M"), People("Adam", "Sandler", 32, "M"), People("Jack", "Marro", 28, "M")]
fp = open("abc","w")
for person in ppl:
fp.write("F.Name: "+person.fname+ "\nLName: "+ person.lname+ "\nAge: "+ str(person.age)+ "\nGender: "+ person.gender+"\n\n")
fp.close()
答案 0 :(得分:1)
在Python中有一个名为list comprehensions的东西。列表推导是你的朋友。
获取所有ppl.fname
:
all_fnames = [person.fname for person in ppl]
让所有ppl.age
超过30的人
all_greater_than_thirty = [person for person in ppl if person.age > 30]
等等。
编辑由于列表推导会返回一个列表,您只需使用它来代替原来的列表,例如写入文件:
with open("abc", "w") as fp:
for person in [p for p in ppl if p.age > 30]:
fp.write(...) # Fill it in with whatever you want to write
甚至更好,但更高级,你会为你的People类创建一个方法,它会返回一个格式化为写入文件的字符串,如People.to_string()
,然后你可以这样做:
with open("abc", "w") as fp:
fp.writelines("%s\n" % person.to_string() for person in ppl if person.age > 30)
优点是效率。而且它看起来更好。
答案 1 :(得分:0)
您可以使用列表理解来获取30岁以上人员的姓名:
names_list = [person.name for person in ppl if person.age > 30]
并做任何你想做的事情:)
答案 2 :(得分:0)
这就是你要找的东西:
for person in [p for p in ppl if (p.fname is "name" and p.age < 30)]:
# Do whatever you want with it...