根据Python2.7类中的变量按字母顺序对类列表进行排序
我想知道是否有一种方法可以让Python2.7对一个列表进行排序,该列表由类中的字符串按字母顺序组成根据Python2.7类中的变量按字母顺序对类列表进行排序,python,list,class,python-2.7,sorting,Python,List,Class,Python 2.7,Sorting,我想知道是否有一种方法可以让Python2.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('firs
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
class-person:#为患者设置
定义初始化(self、FName、LName):
self.FName=FName#患者的名字
self.LName=LName#患者的姓
患者=人(原始输入(“名字”),原始输入(“第二个名字”)
i=1
all=[患者]
医嘱字母表=[患者]
orderInjury=[患者]
打印[0]
当我尝试使用sorted()
方法时,使用key
参数传递lambda,该lambda按照该顺序从该对象中选择FName
和LName
-
sorted_list = sorted(a, key=lambda x: (x.FName, x.LName))
这将对列表进行排序,首先按FName
排序,然后按LName
排序,并返回已排序的列表(它不进行就地排序,因此您可能需要将其重新分配给a
或您希望存储已排序列表的其他名称。假设您希望按患者的姓氏对患者进行排序
课程代码为:
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
这是非常有用的
from operator import attrgetter
a.sort(key=attrgetter('LName')) #sorts in-place
print(a) #list should be sorted here.
attrgetter
也可以接受多个参数。因此,如果您想按姓然后名进行排序,请执行a.sort(key=attrgetter('LName','Fname'))
输出:
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
也可能是重复的
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