易截截图软件、单文件、免安装、纯绿色、仅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中可以使用装饰器对函数进行装饰(或说包装),利用这个特性,可以很方便、简洁地解决一些问题,比如获得函数执行时间的问题。
  首先,我们定义一个函数,如下:
  def exeTime(func):
def newFunc(*args, **args2):
t0 = time.time()
print "@%s, {%s} start" % (time.strftime("%X", time.local ......

python PIL 批量处理处理图片

客户给一堆图片要传到后台,图片太大了,上百张图用photoshop改太慢,就想到用python写个简单的批处理。功能简单就是把原图按比例缩小,代码更简单 20多行。
# -*- coding: cp936 -*-
import Image
import glob, os
#图片批处理
def timage():
for files in glob.glob('D:\\1\\*.JPG'):
filepath,filena ......

python的wiki 列子.

#coding=utf-8
from newtest.wiki.models import WiKi
from django.template import loader, Context
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response

def index(request, pagename=""):
"""显示正常页面,对页面的文字做特殊的链接处理"""
......

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 ......

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 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号