在看《Text Processing in Python》时,看到有关Schwartzian Transform的概念。对于复杂的列表排序很有帮助。

Python的排序很多时候直接使用[ ].sort来实现。而已一般需要定义cmp(item1, item2)(比较)函数作为参数传递给sort。可以简单地如下示例:


def cmp(item1, item2):

psss

li =[]

....

liSorted = li.sort(cmp)

但如果cmp教复杂,直接采用这种方式会效率会比较低。因为每次都需要调用付出的效率比较高。这样就产生了Schwartzian Transform的方式改进排序方法。从wikipedia上可以看出,这种方法属于perl的一个使用惯例。主要思想:

1.于预先计算出一个比较起来很容易的key,如整型。

2.把key和原有的item组合成新的list,这样就可以过滤掉每次需要多次计算的复杂性。

3. 直接对list排序,然后获取排列好的队列。

在Python中可以很方便地采用,比如我们要按照字符串的小写格式来排序:


tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
tmp1.sort()
sorted = [x[1] for x in tmp1]

python中还有不少比较tricky的使用惯例,需要慢慢积累才行。

Tags: .
首页

No Comments Now!

Be the first to comment on this entry.

请您留下评论

名称(必填)
Mail (必填),(will not be published)
网站(recommended)

Fields in bold are required. Email addresses are never published or distributed.

Some HTML code is allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
URLs must be fully qualified (eg: http://www.hongzhixiong.com),and all tags must be properly closed.

Line breaks and paragraphs are automatically converted.

Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.