易截截图软件、单文件、免安装、纯绿色、仅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笔记(7)

  一个Python脚本的开发全过程
问题:完成一个可以为我们所有的重要程序做备份的程序。
步骤拆解:
需要备份的文件和目录由一个列表指定。
文件备份成一个zip文件。
zip存档的名称是当前的日期和时间。
我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使用Info-Zip程序。注意 ......

Python笔记(9)

Python中的文件操作以及输入输出
我们可以分别使用raw_input和print语句来完成这些功能。对于输出,你也可以使用多种多样的str(字符串)类。例如,你能够使用rjust方法来得到一个按一定宽度右对齐的字符串。利用help(str)获得更多详情。
 
 
另一个常用的输入/输出类型是处理文件。创建、读和写文件的能力是 ......

gentoo卸载Python导致emerge不能使用解决方法

今天一不小心把Python给卸载掉了,导致emerge不能使用,最终找到如下解决方案:
wget http://www.python.org/ftp/python/2.4.4/Python-2.4.4.tar.bz2\
tar xjvf Python-2.4.4.tar.bz
cd Python-2.4.4
./configure –with-fpectl –infodir=/usr/share/info/ –mandir=/usr/share/man
make
make instal ......

很好的c++和Python混合编程文章

http://www.cppblog.com/jacky2019/archive/2007/05/17/24269.html
c++中嵌入python入门1
本人是用vc2003+python2.5学习的,其它的也应该差不了多少
0. 坏境设置
把python的include/libs目录分别加到vc的include/lib directories中去。另外,由于python没有提供debug lib,体地说,就是没有提供python25_d.lib了。你可 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号