本文介绍了按类python 2.7中的变量按字母顺序排序类的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法使Python 2.7按照字母顺序由类中的字符串组成的列表排序。

  class person:#set up for patient 
def __init __(self,FName,LName):
self.FName = FName#患者的名字
self.LName = LName#患者的姓氏

patients = person(raw_input('first name'),raw_input('second name'))
i = 1
all =
orderAlphabet = [patients]
orderInjury = [patients]
print a [0]
while i patients = person(raw_input ),raw_input('second name'))
a.append(patients)
i = i + 1

我在此示例中尝试按姓氏排序。

解决方案

非常实用为此。

 从操作符import attrgetter 
a.sort(key = attrgetter('LName'))#sorts in-place
print(a)#list应该在这里排序。

attrgetter 也可以接受多个参数。所以,如果你想按姓氏排序,然后按名字,然后 a.sort(key = attrgetter('LName','Fname')) p>

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'))

这篇关于按类python 2.7中的变量按字母顺序排序类的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 05:09