Perl-Python-a-Day:排序 [英] Perl-Python-a-Day: Sorting

查看:77
本文介绍了Perl-Python-a-Day:排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

排序列表


Xah Lee,200510

在此页面中,我们将展示如何在Python中对列表进行排序。 Perl和

讨论一些类比数据。


要在Python中对列表进行排序,请使用a ?? sorta ??方法。例如:


li = [1,9,2,3];

li.sort();

打印li;

注意sort是一种方法,并且列表已经就地更改了。


假设你有一个矩阵,并且想要按秒排序专栏。

示例解决方案:


li = [[2,6],[1,3],[5,4]]

li.sort(lambda x,y:cmp(x [1],y [1]))

print li; #prints [[1,3],[5,4],[2,6]]

a ?? li.sort行(lambda x,y:cmp(x [1], Y [1]))的ΔΣ也可以写成

作为?? li.sort(cmp = lambda x,y:cmp(x [1],y [1]))a ??


sort的参数是两个参数的函数,返回-1,

0,1。这个函数是一个决策函数,告诉sort()如何

决定列表中任何两个元素的顺序。如果第一个

参数是一个?? ??然后第二个参数,函数应该返回

-1。如果相等,则为0.否则,1。


这是一个更复杂的例子。假设你有一个字符串列表。


''my283.jpg''

''my23i.jpg''

''web7-s.jpg''

''fris88large.jpg''

....

你想要按它们排序嵌入其中的数字。你需要的是b $ b,是为一个函数提供sort()方法,它接受两个字符串,并且

比较字符串中的整数。这是解决方案:


li = [

''my283.jpg'',

''my23i。 jpg'',

''web7-s.jpg'',

''fris88large.jpg'',

]


def myComp(x,y):

import re

def getNum(str):return float(re.findall(r') '\d +'',str)[0])

返回cmp(getNum(x),getNum(y))


li.sort( myComp)

print li#returns [''web7-s.jpg'',''my23i.jpg'',''fris88large.jpg'',

' 'my283.jpg'']

在这里,我们定义了一个函数myComp来告诉排序顺序。

通常,人们会使用a ?? lambdaa ??构造,但Python的lambda

构造只能代表最简单的函数。


关于排序的一些数学


一般来说,用于确定任何两个元素b * b元素顺序的函数f必须满足一些约束条件:


a?¢f(a,a) == 0

a?¢如果f(a,b)== 0那么f(b,a)== 0

a?¢如果f(a,b) == 0和f(b,c)== 0,然后f(a,c)== 0.

a?¢如果f(a,b)== - 1和f(b ,c)== - 1,然后f(a,c)== - 1.

a?¢如果f(a,b)== - 1,那么f(b,a)= = 1.

如果比较函数的行为与上面不一样,那么它就不是一致的,这意味着结果是一个??有序的? list实际上可能是不同的取决于语言实现排序的方式。


所有这些的重要性在于你可能想要的真实软件中的

按专门排序对非简单实体列表进行排序。对于

示例,您可能希望在3D空间中对多边形曲面列表进行排序,

,这是出于实现某些计算机图形功能的特殊原因。
说,您希望按空间方向对这些多边形进行排序。它是b / b
这样的高级案例,理解关于

订购的基本数学很重要。否则,你可能会有一个令人困惑的结果

但是无法找到你代码中的任何缺陷。


Python'是一个??排序? method'的可选参数:a ?? keya ??并且

a ?? reversea ??


大多数情况下,排序是为原子元素列表完成的,例如

[3,2,4]。这只是由myList.sort()完成而没有任何参数。

除了简单列表之外,sort经常用于矩阵(例如

[[2,6], [1,3],[5,4])。对于矩阵,几乎总是一个特定的列

用于订购的基础。例如,如果我们想按第二列

排序,我们可以:a ?? li.sort(lambda x,y:cmp(x [1],y [1]))a? ?。由于这经常被使用,因此Python通过指定用作排序a?keya ??的列,为

提供了更短的语法。对于

例如:


li = [[2,6],[1,3],[5,4]]

li.sort(key = lambda x:x [1])#相当于以下

#li.sort(lambda x,y:cmp(x [1],y [1 ]))

print li; #printed [[1,3],[5,4],[2,6]]

因为Python的实现不是很精致,所以这个专门的

语法实际上比一般形式快得多 - 一个lambda x,y:

cmp(x [1],y [1])a ??。程序员总是使用

a ?? keya?语法特性,如果他正在排序一个大矩阵。


另一个特殊条款是可选的?? ?? reversea ??参数。

当使用a ?? keya ??

参数时,这个参数有些必要。可以通过使用a ?? reversea ??

关键字作为排序参数来反转排序。示例:


以下是等价的:


li.sort(key = lambda x:x [1],reverse = True)

li.sort(lambda x,y:cmp(x [1],y [1]),reverse = True)

li.sort(lambda x,y: cmp(y [1],x [1]))

关于Python排序方法的官方文档位于(下):
http://python.org/doc/2.4/lib/typesseq-mutable.html


按Perl排序


(将在几天内发布)


这个帖子存档于:
http://xahlee.org/perl -python / sort_list.html


Xah
xa*@xahlee.org

a ?? http://xahlee.org/

Sort a List

Xah Lee, 200510

In this page, we show how to sort a list in Python & Perl and also
discuss some math of sort.

To sort a list in Python, use the a??sorta?? method. For example:

li=[1,9,2,3];
li.sort();
print li;
Note that sort is a method, and the list is changed in place.

Suppose you have a matrix, and you want to sort by second column.
Example Solution:

li=[[2,6],[1,3],[5,4]]
li.sort(lambda x, y: cmp(x[1],y[1]))
print li; # prints [[1, 3], [5, 4], [2, 6]]
The line a??li.sort(lambda x, y: cmp(x[1],y[1]))a?? can also bewritten
as a??li.sort(cmp=lambda x, y: cmp(x[1],y[1]))a??

The argument to sort is a function of two arguments, that returns -1,
0, 1. This function is a decision function that tells sort() how to
decide the order of any two elements in your list. If the first
argument is a??lessa?? then second argument, the function should return
-1. If equal, then 0. Else, 1.

Here''s a more complex example. Suppose you have a list of strings.

''my283.jpg''
''my23i.jpg''
''web7-s.jpg''
''fris88large.jpg''
....
You want to sort them by the number embedded in them. What you have to
do, is to provide sort() method a function, that takes two strings, and
compares the integer inside the string. Here''s the solution:

li=[
''my283.jpg'',
''my23i.jpg'',
''web7-s.jpg'',
''fris88large.jpg'',
]

def myComp (x,y):
import re
def getNum(str): return float(re.findall(r''\d+'',str)[0])
return cmp(getNum(x),getNum(y))

li.sort(myComp)
print li # returns [''web7-s.jpg'', ''my23i.jpg'', ''fris88large.jpg'',
''my283.jpg'']
Here, we defined a function myComp to tell sort about the ordering.
Normally, one would use the a??lambdaa?? construct, but Python''s lambda
construct can only represent the simplest functions.

Some Math about Sorting

In general, the function f used to determine the order of any two
element must satisfy some constraints:

a?¢ f(a,a)==0
a?¢ if f(a,b)==0 then f(b,a)==0
a?¢ if f(a,b)==0 and f(b,c)==0, then f(a,c)==0.
a?¢ if f(a,b)==-1 and f(b,c)==-1, then f(a,c)==-1.
a?¢ if f(a,b)==-1, then f(b,a)==1.
If the comparison function does not behave as the above, then it is not
consistent, meaning that the result a??ordereda?? list is may actually
be different depending how the language happens to implement sort.

The significance of all these is that in real software you may want to
sort a list of non-simple entities by a specialized ordering. For
example, you may want to sort a list of polygonal surfaces in 3D space,
for particular reasons in implementing some computer graphics features.
Say, you want to sort these polygons by their spacial orientations. It
is in advanced cases like these, understanding the basic math about
ordering is important. Otherwise, you might have a bewildering result
yet unable to locate any flaws in your code.

Python''s a??sorta?? method''s optional parameters: a??keya?? and
a??reversea??

Most of the time, sorting is done for a list of atomic element such as
[3,2,4]. This is simply done by myList.sort() without any argument.
Other than simple list, sort is frequently used on matrixes (e.g.
[[2,6],[1,3],[5,4]]). For matrixes, almost always a particular column
is used for the basis of ordering. For example, if we want to sort by
second column, we do: a??li.sort(lambda x, y: cmp(x[1],y[1]))a??. Since
this is frequently used, Python provides a somewhat shorter syntax for
it, by specifying the column used as the ordering a??keya??. For
example:

li=[[2,6],[1,3],[5,4]]
li.sort(key=lambda x:x[1] ) # is equivalent to the following
#li.sort(lambda x, y: cmp(x[1],y[1]))
print li; # prints [[1, 3], [5, 4], [2, 6]]
Because Python''s implementation is not very refined , this specialized
syntax is actually much speedier than the general form a??lambda x, y:
cmp(x[1],y[1])a??. It is a burden on the programer to always use the
a??keya?? syntax idiosyncrasy if he is sorting a large matrix.

Another idiosyncratic provision is the optional a??reversea?? argument.
This parameter is somewhat necessary when using the a??keya??
parameter. One can reverse the ordering by using the a??reversea??
keyword as a argument to sort. Example:

The following are equivalent:

li.sort(key=lambda x:x[1], reverse=True )
li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True)
li.sort(lambda x, y: cmp(y[1],x[1]))
The official doc on Python''s sort method is at (bottom):
http://python.org/doc/2.4/lib/typesseq-mutable.html

Sorting in Perl

(to be posted in a couple of days)

This post is archived at:
http://xahlee.org/perl-python/sort_list.html

Xah
xa*@xahlee.org
a?? http://xahlee.org/

推荐答案

Followup-To:comp.lang.scheme


" Xah Lee" < xa*@xahlee.org>写道:
Followup-To: comp.lang.scheme

"Xah Lee" <xa*@xahlee.org> writes:
由于这是经常使用的,因此Python通过指定用作排序a ?? keya的列来为它提供更短的语法。
[...]因为Python的实现不是很精致,所以这种专门的语法实际上比一般形式快得多...... lambda x,y:
cmp(x [1],Y [1])的ΔΣ。程序员总是使用
a ?? keya?语法特质如果他正在排序一个大矩阵。
Since this is frequently used, Python provides a somewhat shorter
syntax for it, by specifying the column used as the ordering a??keya??. [...] Because Python''s implementation is not very refined , this specialized
syntax is actually much speedier than the general form a??lambda x, y:
cmp(x[1],y[1])a??. It is a burden on the programer to always use the
a??keya?? syntax idiosyncrasy if he is sorting a large matrix.




这不仅对人类来说更清晰,而且对所有人来说也更快

支持该语言的所有语言的实现,除非

排序函数非常简单。它被称为Schwartzian变换

,我希望更多的语言设计师和程序员知道它。

http://en.wikipedia.org/wiki/Schwartzian_transform


我敦促未来的SRFI作者包括它。撤回的SRFI-32 for

排序并没有这样做,我找不到任何其他SRFI来处理

并进行排序。
< br $>
-

__("< Marcin Kowalczyk

\ __ / qr **** @ knm.org.pl

^^ http://qrnik.knm.org.pl/~qrczak/



It''s not only clearer for a human, but also faster in all good
implementations of all languages which support that, except when the
ordering function is very simple. It''s called Schwartzian transform
and I wish more language designers and programmers knew about it.

http://en.wikipedia.org/wiki/Schwartzian_transform

I urge future SRFI authors to include it. The withdrawn SRFI-32 for
sorting didn''t do that, and I can''t find any other SRFI which deals
with sorting.

--
__("< Marcin Kowalczyk
\__/ qr****@knm.org.pl
^^ http://qrnik.knm.org.pl/~qrczak/


Xah Lee写道:
Xah Lee wrote:
要在Python中对列表进行排序,请使用a ?? sorta ??方法。例如:

li = [1,9,2,3];
li.sort();
打印li;


同样在Common Lisp中。在Scheme中可能包含

我已经道歉了不再流利了。


CL-USER>(setf list(sort''(1 9 2 3)#''<));输入

(1 2 3 9);输出


第二个参数也是强制性的(比较函数)。

N注意sort是一种方法,并且列表已就地更改。


同样在这里。为安全起见,请将结果分配给list。

假设您有一个矩阵,并且您希望按第二列排序。
示例解决方案:
li = [[2,6],[1,3],[5,4]]
li.sort(lambda x,y:cmp(x [1],y [1]))
print li; #打印[[1,3],[5,4],[2,6]]


CL-USER> (setf list(sort''((2 6)(1 3)(5 4))

#''(lambda(xy)(<(second x)(second y))) ))

((1 3)(5 4)(2 6));输出

sort的参数是两个参数的函数,返回-1,
0,1。这个函数是一个判断函数,告诉sort()如何
决定列表中任何两个元素的顺序。如果第一个
参数是?? ??然后第二个参数,函数应该返回
-1。如果相等,则为0.否则,1。


在CL中,您只需要小于函数。我想如果元素是

相等,他们也不需要排序。

li = [
''my283.jpg'',
''my23i.jpg'',
''web7-s.jpg'',
''fris88large.jpg'',
]


CL-USER> (setf list''(" my283.jpg"" my23i.jpg"" web7-s.jpg"

" fris88large.jpg"))

def myComp(x,y):
import re
def getNum(str):return float(re.findall(r''\ +'',str)[0])
return cmp(getNum(x),getNum(y))


CL-USER> (defun my-comp(xy)

(flet((getnum(s)

(parse-integer s:start(position-if#''digit-char- p s)

:junk-allowed t)))

(<(getnum x)(getnum y))))

li .sort(myComp)
print li#returns [''web7-s.jpg'',''my23i.jpg'',''fris88large.jpg'',
''my283.jpg' ']


CL-USER> (setf list(排序列表#''my-comp))

(" web7-s.jpg"" my23i.jpg"" fris88large.jpg"" my283.jpg") ;输出

li = [[2,6],[1,3],[5,4]]
li.sort(key = lambda x:x [1])#is相当于以下
#li.sort(lambda x,y:cmp(x [1],y [1]))
print li; #printed [[1,3],[5,4],[2,6]]
To sort a list in Python, use the a??sorta?? method. For example:

li=[1,9,2,3];
li.sort();
print li;
Likewise in Common Lisp. In Scheme there are probably packages for that
as well. My apologies for not being very fluent anymore.

CL-USER> (setf list (sort ''(1 9 2 3) #''<)) ; input
(1 2 3 9) ; output

The second argument is mandatory too (comparison function).
Note that sort is a method, and the list is changed in place.
Same here. To be safe, assign the result to "list".
Suppose you have a matrix, and you want to sort by second column.
Example Solution:

li=[[2,6],[1,3],[5,4]]
li.sort(lambda x, y: cmp(x[1],y[1]))
print li; # prints [[1, 3], [5, 4], [2, 6]]
CL-USER> (setf list (sort ''((2 6) (1 3) (5 4))
#''(lambda (x y) (< (second x) (second y)))))
((1 3) (5 4) (2 6)) ; output
The argument to sort is a function of two arguments, that returns -1,
0, 1. This function is a decision function that tells sort() how to
decide the order of any two elements in your list. If the first
argument is a??lessa?? then second argument, the function should return
-1. If equal, then 0. Else, 1.
In CL you only need a smaller-than function. I guess if elements are
"equal", they don''t need sorting anyway.
li=[
''my283.jpg'',
''my23i.jpg'',
''web7-s.jpg'',
''fris88large.jpg'',
]
CL-USER> (setf list ''("my283.jpg" "my23i.jpg" "web7-s.jpg"
"fris88large.jpg"))
def myComp (x,y):
import re
def getNum(str): return float(re.findall(r''\d+'',str)[0])
return cmp(getNum(x),getNum(y))
CL-USER> (defun my-comp (x y)
(flet ((getnum (s)
(parse-integer s :start (position-if #''digit-char-p s)
:junk-allowed t)))
(< (getnum x) (getnum y))))
li.sort(myComp)
print li # returns [''web7-s.jpg'', ''my23i.jpg'', ''fris88large.jpg'',
''my283.jpg'']
CL-USER> (setf list (sort list #''my-comp))
("web7-s.jpg" "my23i.jpg" "fris88large.jpg" "my283.jpg") ; output
li=[[2,6],[1,3],[5,4]]
li.sort(key=lambda x:x[1] ) # is equivalent to the following
#li.sort(lambda x, y: cmp(x[1],y[1]))
print li; # prints [[1, 3], [5, 4], [2, 6]]




CL-USER> (setf list(sort''((2 6)(1 3)(5 4))#''<:key#''second))

((1 3)(5 4 )(2 6));输出


这里有些人可能会跳进去说列表可能比矢量更具可读性b / b
但是列表很慢。

如果他们的数据集速度很慢,只需使用向量;)


-

州,来自友好人士的新宗教谁给你带来了法西斯主义。



CL-USER> (setf list (sort ''((2 6) (1 3) (5 4)) #''< :key #''second))
((1 3) (5 4) (2 6)) ; output

Here some people might jump in and say "lists might be more readable
than vectors, but lists are slow."
If they are slow for your data set, just use vectors instead ;)

--
State, the new religion from the friendly guys who brought you fascism.


Ulrich Hobelmann写道:
Ulrich Hobelmann wrote:
Xah Lee写道:
Xah Lee wrote:
要排序Python中的列表,使用a ?? sorta ??方法。例如:

li = [1,9,2,3];
li.sort();
打印li;
To sort a list in Python, use the a??sorta?? method. For example:

li=[1,9,2,3];
li.sort();
print li;


。我为不再流利而道歉。

CL-USER> (setf list(sort''(1 9 2 3)#''<));输入
(1 2 3 9);输出



Likewise in Common Lisp. In Scheme there are probably packages for that
as well. My apologies for not being very fluent anymore.

CL-USER> (setf list (sort ''(1 9 2 3) #''<)) ; input
(1 2 3 9) ; output




小心。 Common Lisp的sort函数被指定为破坏性的,所以你不应该在文字常量上使用它。所以不要说(排序''(1 9 2 3)

....),说(排序(列表1 9 2 3)......)等。

Pascal


-

OOPSLA '05关于通用功能的教程& CLOS元对象协议

++++请参阅 http ://p-cos.net/oopsla05-tutorial.html 了解更多详情++++



Careful. Common Lisp''s sort function is specified to be destructive, so
you shouldn''t use it on literal constants. So don''t say (sort ''(1 9 2 3)
....), say (sort (list 1 9 2 3) ...), etc.
Pascal

--
OOPSLA''05 tutorial on generic functions & the CLOS Metaobject Protocol
++++ see http://p-cos.net/oopsla05-tutorial.html for more details ++++


这篇关于Perl-Python-a-Day:排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆