对列表进行排序(自定义)

问题

users = [{'name': 'u2', 'age': 18, 'foo': 'a'},
         {'name': 'coldplay', 'age': 19, 'foo': 'b'},
         {'name': 'pink floyd', 'age': 25, 'foo': 'c'},
         {'name': 'the door', 'age': 15, 'foo': 'd'},
         {'name': 'eminem', 'age':40, 'foo': 'e'},
         {'name': '2pac', 'age':50, 'foo': 'f'},
         {'name': 'armstrong', 'age':60, 'foo': 'g'},
         {'name': 'ABBA', 'age':25, 'foo': 'h'}
        ]

按年龄排序

operator.itemgetter

from operator import itemgetter
print sorted(users, key=itemgetter('age'))

上面的结果中,我们发现有两个元素age相同,我们希望如果年龄相同,则按姓名排序呢?事实上,itemgetter可以传入两个参数。

print sorted(users, key=itemgetter('age','name'))

如果要给不支持比较操作的对象排序呢?

class Foo:
    def __init__(self,x):
        self.x = x

test = [Foo(12), Foo(23),Foo(5),Foo(3),Foo(8),Foo(66)]
test = sorted(test)
for t in test:
    print t.x

上面的代码中,我们创建了一个新的类,试图给一组Foo类的对象进行排序,但是失败了。思考一下,为啥int之间可以比较呢?原因很简单,因为int实现了cmp方法

print int.__cmp__

要想让Foo对象可以排序,首先我们要给Foo对象实现cmp方法

class Foo:
    def __init__(self,x):
        self.x = x

    def __cmp__(self, other):
        if self.x < other.x:
            return -1
        elif self.x > other.x:
            return 1
        else:
            return 0

assert Foo(13) > Foo(12)
assert Foo(12) == Foo(12)
assert Foo(11) < Foo(12)

test = [Foo(12), Foo(23),Foo(5),Foo(3),Foo(8),Foo(66)]
test = sorted(test)
for t in test:
    print t.x

现在Foo类的对象可比较了,也就可以排序了。

operator.attrgetter

from operator import attrgetter
test = [Foo(12), Foo(23),Foo(5),Foo(3),Foo(8),Foo(66)]
test2 = sorted(test, key=lambda t : t.x)
test1 = sorted(test, key=attrgetter('x'))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,671评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,969评论 19 139
  • 接着上节 mutex,本节主要介绍atomic的内容,练习代码地址。本文参考http://www.cplusplu...
    jorion阅读 73,975评论 1 14
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 9,754评论 0 16
  • 2017.12.26 19:15pm-23:40pm 今天湖州照例是冷地不可言说的天,昨晚敲完字后,脑子昏沉好一会...
    少年阿段阅读 1,121评论 0 0

友情链接更多精彩内容