How to search in a list of objects attribute ? Suppose i want the fname of all object and also the age > 30 or some match found
#!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()
In Python there's a thing called list comprehensions . And list comprehensions are your friend.
Get all ppl.fname
:
all_fnames = [person.fname for person in ppl]
Get all persons with ppl.age
greater than 30:
all_greater_than_thirty = [person for person in ppl if person.age > 30]
And so on.
EDIT Since a list comprehension returns a list, you would just use that in place of whatever list you originally had, for example to write to file:
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
Or even better, but more advanced, you would create a method for your People class that would return a string formatted to write to file, something like People.to_string()
, then you could do this:
with open("abc", "w") as fp:
fp.writelines("%s\n" % person.to_string() for person in ppl if person.age > 30)
The advantage is efficiency. Plus it looks nicer.
You can get the names of people older than 30 using list comprehension:
names_list = [person.name for person in ppl if person.age > 30]
and do whatever you want to do with them :)
Is this what you're looking for:
for person in [p for p in ppl if (p.fname is "name" and p.age < 30)]:
# Do whatever you want with it...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.