博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python中的字典排序
阅读量:6794 次
发布时间:2019-06-26

本文共 6008 字,大约阅读时间需要 20 分钟。

我想将 b = {'a':234,'b':1,'c':2,'e':2387} 分别按照key和value进行排序,该怎样办呢?

Python中比较常用的排序有两个函数,

一、定义

(1)一个是List数据结构中的sort

>>> help(list.sort)

Help on method_descriptor:

sort(...)

L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

 

  1. The sort() method takes optional arguments for controlling the comparisons.

    cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

    key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

    reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

    In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use to convert an old-style cmp function to a key function.

    Changed in version 2.3: Support for None as an equivalent to omitting cmp was added.

    Changed in version 2.4: Support for key and reverse was added.

 

(2)内置的函数sorted

sorted(iterable[, cmp[, key[, reverse]]])

Return a new sorted list from the items in iterable.

表明内置的sorted函数会生成一个新的数据表不会改变原有数据的顺序。

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section ).

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use to convert an old-style cmp function to a key function.

 

二、举例

Sorting Basics

>>>sorted([5, 2, 3, 1, 4])[1, 2, 3, 4, 5]
>>> a = [5, 2, 3, 1, 4]>>> a.sort()>>> a[1, 2, 3, 4, 5] 第一种使用的是内置排序方法,第二种是list的排序方法。Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.(虽然第一种方法不是很方便,但是通常更有效率)
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})[1, 2, 3, 4, 5]

Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable. 

(另外一点就是list.sort()的方法仅仅只能用作列表的数据结构,然而,sorted却可以用作任何可迭代的数据结构)

 

Key Functions

Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons(从2.4以后,新添加了key参数,通过制定一个判断函数来按照key进行排序)

>>> sorted("This is a test string from Andrew".split(), key=str.lower)['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
>>> student_tuples = [        ('john', 'A', 15),        ('jane', 'B', 12),        ('dave', 'B', 10),]>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 关于lambda实际上为匿名函数,后面部分会将 lambda 函数参数:返回值
>>> class Student:        def __init__(self, name, grade, age):                self.name = name                self.grade = grade                self.age = age def __repr__(self): return repr((self.name, self.grade, self.age)) def weighted_grade(self): return 'CBA'.index(self.grade) / float(self.age) >>> student_objects = [ Student('john', 'A', 15), Student('jane', 'B', 12), Student('dave', 'B', 10), ] >>> sorted(student_objects, key=lambda student: student.age) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator Module Functions

The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.

Using those functions, the above examples become simpler and faster. 

通过引入operator模块有了更快的查询方式:

>>> from operator import itemgetter, attrgetter, methodcaller>>> sorted(student_tuples, key=itemgetter(2))[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]>>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age: 

(我们不仅可以按照一种条件进行排序,我们还可以设定多个条件进行排序,如下例中的先按照班级,在按照年龄)

>>> sorted(student_tuples, key=itemgetter(1,2))[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]>>> sorted(student_objects, key=attrgetter('grade', 'age'))[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

Ascending and Descending(升降序)

仅仅在后面添加一个reverse就可以了 >>> sorted(student_tuples, key=itemgetter(2), reverse=True)[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>> sorted(student_objects, key=attrgetter('age'), reverse=True)[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] 回到刚开始的地方,我们可以很轻松的写出:

import operator

def sortDict():
b = {'a':234,'b':1,'c':2,'e':2387}
print(sorted(b.iteritems(),key=operator.itemgetter(0)))#按key升序排列
print(sorted(b.iteritems(),key=operator.itemgetter(1)))#按value升序排列
print(sorted(b.items(),key=lambda x:x[1],reverse=True))##按value降序排列

输出结果:

[('a', 234), ('b', 1), ('c', 2), ('e', 2387)]

[('b', 1), ('c', 2), ('a', 234), ('e', 2387)]
[('e', 2387), ('a', 234), ('c', 2), ('b', 1)]

 
 
 
 
 

转载于:https://www.cnblogs.com/CBDoctor/p/4090900.html

你可能感兴趣的文章
nginx下配置多站点
查看>>
Adding a prefix header to an iOS project
查看>>
Perl 机选 双色球
查看>>
Linux操作系统基础解析之(七)——Bash(Shell)基础知识(5)
查看>>
LDAP认证vsftp方法
查看>>
通过RS232发送和接收短信(三)
查看>>
国内第一篇详细讲解hadoop2的automatic HA+Federation+Yarn的教程(1)
查看>>
在Centos下配置Rsync服务器
查看>>
异步超时后直接返回
查看>>
利用IT手段严防偷盗票房
查看>>
记《浪潮之巅》-第一版-2.蓝色巨人--IBM
查看>>
linux 系统安装后网卡配置,解决不能上网(重启后不能上网)(新手篇)
查看>>
有类路由与无类路由的区别
查看>>
企业网下の帧中继网络
查看>>
我的友情链接
查看>>
F5新型数据中心防火墙
查看>>
F5荣获网络优化类别年度最佳HP AllianceOne合作伙伴奖项
查看>>
Windows Phone:使用三方(多方)通话的电话会议
查看>>
Exchange2010和2013共存后IMAP问题
查看>>
38 tomcat lb cluster、memcached和msm、msm及jvm虚拟机性能监控、tcpdump和nc工具的使用...
查看>>