I was wondering if there was a way to make python 2.7 sort a list that is made up of classes alphabetically by a string inside the class.
class person: #set up for patient
def __init__(self, FName, LName):
self.FName = FName # the first name of patient
self.LName = LName # last name of patient
patients=person(raw_input('first name'),raw_input('second name'))
i=1
all=[patients]
orderAlphabet=[patients]
orderInjury=[patients]
print a[0]
while i<3:
patients=person(raw_input('first name'),raw_input('second name'))
a.append(patients)
i = i+1
I am trying to sort by last name in this example.
operator.attrgetter
is pretty useful for this.
from operator import attrgetter
a.sort(key=attrgetter('LName')) #sorts in-place
print(a) #list should be sorted here.
attrgetter
can also take multiple arguments. So, if you wanted to sort by, say, last name then first name, do a.sort(key=attrgetter('LName', 'Fname'))
Let's say you want to sort the patients by their last name.
The class code would be:
class person: #set up for patient
def __init__(self, FName, LName):
self.FName = FName # the first name of patient
self.LName = LName # last name of patient
You would take inputs from the user using:
i = 1
patients=person(raw_input('first name'),raw_input('second name'))
a=[patients] #You have used 'all'
while(i < 3):
patients=person(raw_input('first name'),raw_input('second name'))
a.append(patients) #And you have used 'a' here.
i = i + 1
To sort the patients by their last name, you could use:
orderAlphabet=[a[i].LName for i in range(0,3)]
orderAlphabet = orderAlphabet.sort()
Try using sorted()
method with key
argument passing a lambda that selects the FName
and LName
from that object, in that order -
sorted_list = sorted(a, key=lambda x: (x.FName, x.LName))
This would sort the list , first by FName
then by LName
and return the sorted list (It does not do inplace sorting, so you may have to reassign it to a
or some other name that you want to store the sorted list in.
class person: #set up for patient
def __init__(self, FName, LName):
self.FName = FName # the first name of patient
self.LName = LName # last name of patient
def __str__(self,):
return 'FName:'+ self.FName + ', LName:' + self.LName
persons = [person('1', 'd'), person('3', 'c'), person('2', 'b')]
persons2 = sorted(persons, key=lambda p: p.FName) # sort by FName
persons3 = sorted(persons, key=lambda p: p.LName) # sort by LName
persons4 = sorted(persons, key=lambda p: p.LName, reverse=True) # sort by LName with reverse order
for p in persons2:
print p
print
for p in persons3:
print p
print
for p in persons4:
print p
output:
FName:1, LName:d
FName:2, LName:b
FName:3, LName:c
FName:2, LName:b
FName:3, LName:c
FName:1, LName:d
FName:1, LName:d
FName:3, LName:c
FName:2, LName:b