Python的lambda函数与排序

前几天看到了一行求1000的阶乘的Python代码:

print   reduce(lambda   x,y:x*y,   range(1,   1001))

一下子被python代码的精简与紧凑所折服,故对代码进行了简单的分析。

reduce与range都是Python的内置函数。

range(1,1001)表示生成1到1000的连续整数列表(List)。

 

 

reduce(functionA,iterableB),functionA为需要两个变量的函数,并返回一个值。iterableB为可迭代变量,如List等。reduce函数将B中的元素从左到右依次传入函数A中,再用函数A返回的结果替代传入的参数,反复执行,则可将B reduce成一个单值。在此,是将1到1000的连续整数列表传入lambda函数并用两个数的积替换列表中的数,实际的计算过程为:(…((1×2)×3)×4)×…×1000),最后的结果即1000的阶乘。

下面来介绍一下lambda函数。

lambda函数是一种快速定义单行的最小函数,是从 Lisp 借用来的,可以用在任何需要函数的地方。下面的例子比较了传统的函数与lambda函数的定义方式:

1 >>> def f(x,y):
2 …     return x*y
3 …    
4 >>> f(2,3)
5 6
6 >>> g = lambda x,y: x*y
7 >>> g(2,3)
8 6

可以看到,两个函数得到的结果一样,而对于实现简单功能的函数来说,使用lambda函数来定义更加精简灵活,还可以直接把函数赋值给一个变量,用变量名来表示函数名。

其实lambda函数在很多时候都是不需要赋值给一个变量的(如前文中求阶乘的过程)。使用lambda函数还有一些注意事项:
lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值。
lambda 函数不能包含命令,包含的表达式不能超过一个。下面简单演示一下如何使用lambda函数实现自定义排序。 01 class People:
02     age=0
03     gender=’male’
04
05     def __init__(self, age, gender): 
06         self.age = age 
07         self.gender = gender
08     def toString(self):
09         return ‘Age:’+str(self.age)+’\tGender:’+self.gender
10
11 List=[People(21,'male'),People(20,'famale'),People(34,'male'),People(19,'famale')]
12 print ‘Befor sort:’
13 for p in List:
14     print p.toString()
15
16 List.sort(lambda p1,p2:cmp(p1.age,p2.age))
17 print ‘\nAfter ascending sort:’
18 for p in List:
19     print p.toString()
20
21 List.sort(lambda p1,p2:-cmp(p1.age,p2.age))
22 print ‘\nAfter descending sort:’
23 for p in List:
24     print p.toString()

上面的代码定义了一个People类,并通过lambda函数,实现了对包含People类对象的列表按照People的年龄,进行升序和降序排列。运行结果如下:

Befor sort:
Age:21    Gender:male
Age:20    Gender:famale
Age:34    Gender:male
Age:19    Gender:famale

After ascending sort:
Age:19    Gender:famale
Age:20    Gender:famale
Age:21    Gender:male
Age:34    Gender:male

After descending sort:
Age:34    Gender:male
Age:21    Gender:male
Age:20    Gender:famale
Age:19    Gender:famale

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. 序列、元组、列表、字典

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu