2015-07-19 69 views
0

我是Python新手。我有一个对象列表,每个对象是一个类的实例,每个对象有5个值。我需要根据两个值对列表进行排序。即名和姓。我怎样才能做到这一点?还是有更好的方法来实现我正在做的事情?如何基于Python中的对象的多个值对一系列类实例(对象)进行排序

还有没有办法在排序后以json格式列出此列表中的所有对象?

class Format1(): 
    def __init__(self, alist): 
     self.color = alist[3] 
     self.firstname = alist[1] 
     self.lastname = alist[0] 
     self.phonenumber = alist[2] 
     self.zipcode = alist[4] 

obj = Format1(alist) 
entries.append(obj) 
+1

你可以显示你的代码吗? –

+0

OBJ =格式1(ALIST) entries.append(OBJ) 类格式1(): \t DEF __init __(个体,ALIST): \t \t self.color = ALIST [3] \t \t self.firstname = ALIST [1] \t \t self.lastname = ALIST [0] \t \t self.phonenumber = ALIST [2] \t \t self.zipcode = ALIST [4] 所以我创建使用上述类的多个对象和添加对象列表。 – redAlert

+0

你可以请[编辑]你的问题,包括代码? – NightShadeQueen

回答

0

对于排序,您可以使用sorted()功能与key参数作为 -

sortedlist = sorted(alist, key=lambda x: (x.firstname , x.lastname)) 

另外,如果通过JSON格式,你的意思是这样 -

{'color':'<colorname>', 'firstname','<firstname>' ....} 

这样一个字典为每个对象。然后,您可以创建一个返回对象的__dict__属性的功能和使用json.dumpsmap像 -

def cdict(a): 
    return a.__dict__ 

s = json.dumps(list(map(cdict,<your list>))) 
print(s) 
0
sorted = sorted(alist, key=lambda x: (x['firstname'], x['lastname'])) 
+0

你假设他已经实现了__getitem__方法。他没有将这些数据存储在json中,所以这段代码在代码方面不适合他目前的工作。 – blasko

+0

是的。使用上述方法获取__getitem__错误 – redAlert

0

如果你想使用Kremlan的答案,以下内容添加到您的类:

def __getitem__(self, option): 
     return {"color": self.color, 
       "firstname": self.firstname, 
       "lastname": self.lastname 
       "phonenumber": self.phonenumber 
       "zipcode": self.zipcode 
     }.get(option.lower(), None) 
0

我喜欢使用operator.attrgetter使事情变得更具描述性/可读性

import operator 
last_then_first = operator.attrgetter('lastname', 'firstname') 
entries.sort(key = last_then_first) 
相关问题