1

如何在对象属性列表中搜索?假设我想要所有对象的 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()
4

3 回答 3

2

在 Python 中有一个叫做列表推导的东西。列表推导是你的朋友。

全部获取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)

优点是效率。另外它看起来更好。

于 2013-10-18T07:26:13.507 回答
0

这是你要找的:

for person in [p for p in ppl if (p.fname is "name" and p.age < 30)]:
    # Do whatever you want with it...
于 2013-10-18T07:28:05.547 回答
0

您可以使用列表推导获取 30 岁以上的人的姓名:

names_list = [person.name for person in ppl if person.age > 30]

并为他们做任何你想做的事:)

于 2013-10-18T07:25:51.647 回答