Python内置了一些特殊函数,这些函数很具python特性。可以让代码更加简洁。

可以看例子:

filter(function, sequence)

str = ['a', 'b','c', 'd']

def fun1(s): return s if s != 'a' else None

ret = filter(fun1, str)

print ret

## ['b', 'c', 'd']

对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回。

可以看作是过滤函数。

 2 map(function, sequence) 

str = ['a', 'b','c', 'd'] 

def fun2(s): return s + ".txt"

ret = map(fun2, str)

print ret

## ['a.txt', 'b.txt', 'c.txt', 'd.txt']

对sequence中的item依次执行function(item),见执行结果组成一个List返回:

map也支持多个sequence,这就要求function也支持相应数量的参数输入:
def add(x, y): return x+y 
 print map(add, range(10), range(10)) 
##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


3 reduce(function, sequence, starting_value):def add1(x,y): return x + y

print reduce(add1, range(1, 100))

print reduce(add1, range(1, 100), 20)

## 4950 (注:1+2+...+99)
## 4970 (注:1+2+...+99+20)

对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和: 


4 lambda

g = lambda s: s + ".fsh"

print g("haha")

print (lambda x: x * 2) (3)

## haha.fsh

## 6

这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数.

相关文章:

  • 2022-12-23
  • 2021-07-01
  • 2022-02-26
  • 2022-01-25
  • 2022-12-23
  • 2021-09-09
猜你喜欢
  • 2021-08-06
  • 2022-02-13
  • 2022-02-25
相关资源
相似解决方案