易截截图软件、单文件、免安装、纯绿色、仅160KB

转:Python的sort()

之前学习第九章的排序小结的时候,对sort()排序方法不理解,因为括号里面带了自定义的比较函数。
后来查手册,才发现sort()里面本来就带了这样的参数。能够自定义比较方法,确实很灵活。
不仅如此,在网上查到一个博客,作者不单停留在这表面,还查究了sort()的排序算法,确实有意思。
全文抄录如下:
http://blog.donews.com/maverick/archive/2006/07/09/951101.aspx
学习笔记:Python的排序
Python语言内置了sort方法,可以很方便地对某个List进行排序:
L = [6, 5, 1, 3, 4, 2]
L.sort()
print L
---------- Run Python Program ----------
[1, 2, 3, 4, 5, 6]
某些时候,我们希望按照自己定义的排序规则来排序(例如,按关键词的权重排序,按人的年龄排序,等等)。在Java语言中,我们可以自定义Comparator来实现,Python中也提供了类似的办法。
若List中每个元素都是2-tuple,tuple中第一个元素为String类型的keyword,第二个元素为该字符串对应的权重(int类型),希望按照权重排序(从高到低),则可以这样:
def my_cmp(E1, E2):
    return -cmp(E1[1], E2[1])    #compare weight of each 2-tuple
                    #return the negative result of built-in cmp function
                    #thus we get the descend order
L = [('a', 0), ('b', 1), ('c', 2), ('d', 3)]
L.sort(my_cmp)
print L
---------- Run Python Program ----------
[('d', 3), ('c', 2), ('b', 1), ('a', 0)]
正因为可以自定义cmp方法,我们不妨探究一下,built-in的sort方法,到底是采用的哪一种排序算法:
from random import shuffle
def my_cmp(E1, E2):
    print 'E1:', E1, 'E2:', E2
    return cmp(E1, E2)
L = range(0, 10)
shuffle(L)
print L
L.sort(my_cmp)
---------- Run Python Program ----------
[5, 3, 7, 6, 2, 8, 9, 4, 1, 0]
E1: 3 E2: 5
E1: 7 E2: 3
E1: 7 E2: 5
E1: 6 E2: 5
E1: 6 E2: 7
E1: 2 E2: 6
E1: 2 E2: 5
E1: 2 E2: 3
E1: 8 E2: 5
E1: 8 E2: 7
E1: 9 E2: 6
E1: 9 E2: 8
E1: 4 E2: 6
E1: 4 E2: 3
E1: 4 E2: 5
E1: 1 E2: 6
E1: 1 E2: 4
E1: 1 E


相关文档:

python中的列表排序操作

 
 
 
Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various man ......

Python IDE and GUI Framework for Windows

Pythonwin - Python IDE and GUI Framework for Windows.
Copyright 1994-2006 Mark Hammond
Python is Copyright (c) 2000-2008 ActiveState Software Inc.
Copyright (c) 2001-2008 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-20 ......

《Python语言入门》第九章临时小节

学习了第八章后,紧锣密鼓的开始第九章的学习。
学习了“数据结构操作”,学习了“文件操作”。“数据结构操作”还比较有意思,看得懂。“文件操作”就开始头昏昏的,像脑子进了浆糊。
好不容易看到“操作程序”,才发现“操作程序”这一节的内容并不是我所 ......

python两个dict相加


>>> a = {'1':'2'}
>>> b = {'3':'4'}
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> a.update(b)
>>> a
{'1': '2', '3': '4'} ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号