我想知道是否有办法让python 2.7按照字母顺序按类中的字符串对类进行排序。
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
我试图在这个例子中按姓氏排序。
答案 0 :(得分:2)
我们假设您想按姓氏对患者进行分类。
班级代码是:
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
您可以使用以下方式接收用户的输入:
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
要按照姓氏对患者进行排序,您可以使用:
orderAlphabet=[a[i].LName for i in range(0,3)]
orderAlphabet = orderAlphabet.sort()
答案 1 :(得分:1)
operator.attrgetter
对此非常有用。
Route::group(['middleware' => ['auth','auth_admin']], function () {
// Admin routes here
});
from operator import attrgetter
a.sort(key=attrgetter('LName')) #sorts in-place
print(a) #list should be sorted here.
也可以使用多个参数。因此,如果您想按姓氏排序,然后按名字排序,请执行attrgetter
答案 2 :(得分:0)
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
输出:
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