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 manuals describing them, so I'll do so here.
Backward compatibility note
Many constructs given in the HOWTO assume Python 2.4. Before that, there was no sorted() builtin and list.sort() took no keyword arguments.
Sorting basic data types
A simple ascending sort is very easy: just call the sorted() function. It returns a new sorted list:
>>> print sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
You can also use the sort() method of a list. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> print a
[1, 2, 3, 4, 5]
Sort takes an optional function which can be called for doing the comparisons. The default sort routine is equivalent to using cmp:
>>> print sorted([5, 2, 3, 1, 4], cmp)
[1, 2, 3, 4, 5]
where cmp() is the built-in function that compares two objects, x and y, and returns a negative number, 0 or a positive number depending on whether x<y, x==y, or x>y. During the course of the sort the relationships must stay the same for the final list to make sense.
If you want, you can define your own function for the comparison. For integers we can do:
>>> def numeric_compare(x, y):
>>> return x-y
>>>
Note that this does not work for numbers in general, as the comparison function must return integers.
For numbers in general, but a little more understandably:
>>> def numeric_compare(x, y):
>>> if x>y:
>>> return
——由于最近在做有关网页搜索的项目,涉及到一些编码方面的知识,小弟在网上偶然地发现了这么一篇文章,很易懂,不晦涩,为了方便自己也同时能方便大家,就转了过来,以作参考……
文章出处:http://blog.csdn.net/tingsking18/arc ......
#---------------------转转转转转转转转转转转转转转转转转转转转转转转-------------------------------------------#
Python作为一种功能强大且通用的编程语言而广受好评,它具有非常清晰的语法特点,适用于多种操作系统,目前在国际上非常流行,正在得到越来越多的应用。
下面就让我们一起来看看它的强大 ......
继前篇《Import Module》(http://blog.csdn.net/xiadasong007/archive/2009/09/02/4512797.aspx),继续分析嵌入部分基础知识。这次不多说,有什么问题记得多查英文资料,国内的这方面知识少
还是来看代码,写完我就睡觉了~
#include "python/python.h"
#include <iostream>
using namespace std;
int ......