程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python special syntax: filter, map, reduce, lambda

編輯:Python

In this paper, from  http://www.cnblogs.com/fangshenghui/p/3445469.html


Python Built in some special functions , These functions are very python characteristic . Can make the code more concise .

You can see examples :

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']

Yes sequence Medium item Execute sequentially function(item), The result of execution is True Of item Form a List/String/Tuple( Depending on sequence The type of ) return .

It can be seen as a filter function .

 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']

Yes sequence Medium item Execute sequentially function(item), See the implementation results to form a List return :

map Support multiple sequence, This requires that function It also supports a corresponding number of parameter inputs :
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 ( notes :1+2+...+99)
## 4970 ( notes :1+2+...+99+20)

Yes sequence Medium item Sequential iteration call function, If there is starting_value, It can also be called as an initial value , For example, it can be used to List Sum up : 


4 lambda

g = lambda s: s + ".fsh"

print g("haha")

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

## haha.fsh

## 6

This is a Python Support an interesting grammar , It allows you to quickly define the minimum function of a single line , Similar to C Macro in language , These are called lambda Function of .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved