hmzone 发表于 2017-4-24 08:40:18

Python对象比较

class Myobject(object):
def __init__(self, val):
self.val = val
def __eq__(self,other):
return self.val == other.val
def __gt__(self,other):
return self.val > other.val
a = Myobject(1)
c = Myobject(3)
b = Myobject(2)
print(a>b, a==b, a<b)
l =
for myob in l:
print(myob.val)
l.sort()
for myob in l:
print(myob.val)

# python 2
import functools
@functools.total_ordering
class Myobject(object):
def __init__(self, val):
self.val = val
def __eq__(self,other):
return self.val == other.val
def __gt__(self,other):
return self.val > other.val
a = Myobject(1)
c = Myobject(3)
b = Myobject(2)
print(a>b, a==b, a<b)
l =
for myobject in l:
print(myobject.val)
l.sort()
for myobject in l:
print(myobject.val)


from collections import namedtuple
from operator import itemgetter
Person=namedtuple("Person",'name age email')
f = Person('wow',3,'234@qq.com')
p = Person('tom',44,'uuu@we.com')
o = Person('mary',10,'tttt@tt.ttt')
o2 = Person('jimi',10,'ffff@tt.ttt')
plist =
# 以 age 排序
sp = sorted(plist, key=lambda x:x.age)
for p in sp:
print p
# 多级排序
sp = sorted(plist, key=itemgetter(1,0))
for p in sp:
print p
  输出
  Person(name='wow', age=3, email='234@qq.com')
Person(name='mary', age=10, email='tttt@tt.ttt')
Person(name='jimi', age=10, email='ffff@tt.ttt')
Person(name='tom', age=44, email='uuu@we.com')
  
Person(name='wow', age=3, email='234@qq.com')
Person(name='jimi', age=10, email='ffff@tt.ttt')
Person(name='mary', age=10, email='tttt@tt.ttt')
Person(name='tom', age=44, email='uuu@we.com')
页: [1]
查看完整版本: Python对象比较