我想知道是否有一种方法,使蟒蛇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
我想按姓氏在这个例子中排序。
operator.attrgetter
是这个非常有用的。
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'))
比方说,你想通过自己的姓氏给病人排序。
类代码如下:
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()
尝试使用sorted()
方法用key
参数传递,其选择一个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
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
文章来源: Sorting a list of classes alphabetically based on variable in class python 2.7