Filter
Filter (...) Filter (function or None, sequence), list, tuple, or string
Description
Execute function (item) on item in sequence and execute the result to True (! =0) item consists of a list/string/tuple (depending on the type of sequence) returned, false exits (0) for filtering.
Example:
1>>>defDiv (n):returnn%22 ... 3>>> Filter (Div,range (5))#returns the value of the div output that is not equal to 04[1, 3]5>>> Filter (Div,range (10))6[1, 3, 5, 7, 9]7>>> Filter (LambdaX:x%2,range (10))#The lambda function returns an odd number, returning the list8[1, 3, 5, 7, 9]9>>> Filter (LambdaX: notX%2,range (10))Ten[0, 2, 4, 6, 8] One>>>defFin (n):returnn!='Z' #filter ' z ' function, return False if Z is present A ... ->>> Filter (FIN,'zhoujy')#' z ' is filtered - 'houjy' the>>> Filter (LambdaX:x! ='Z','zhoujy')#Labmda Returns True Value - 'houjy' ->>> Filter (LambdaX: notx=='Z','zhoujy')#return: String - 'houjy'
Map
Map (...) Map (function, sequence[, sequence, ...]) list
Description
Execute function (item) on item in sequence, and the result output is list.
Example:
>>> Map (str, range (5)) #对range (5) for STR operations [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 '] #返回列表 >>> def A DD (n): Return n+n ... >>> map (add, Range (5)) #对range (5) for the add operation [0, 2, 4, 6, 8]>>> map (lambda x: X+x,range (5)) #lambda function, each + itself [0, 2, 4, 6, 8]
>>> map (lambda x:x+1,range) #lambda function, each +1
[1, 2, 3, 4, 5, 6, 7, 8, 9, []
>>> map (Add, ' zhoujy ') [' zz ', ' hh ', ' oo ', ' uu ', ' JJ ', ' yy '] #想要输入 multiple sequences
, need to support multiple parameters of the function, note that the length of each sequence must be the same, otherwise error:>>> def add (x, y): return x+y ... >>> map (add, ' zhoujy ', ' Python ') [' ZP ', ' hy ', ' ot ', ' uh ', ' Jo ', ' yn ']>>> def add (x, Y, z): Return x+y+z ... >>> map (add, ' zhoujy ', ' Python ', ' Test ') # ' test ' is longer than the other 2 small traceback (most recent call last): File "<stdin>", line 1, in <module>typ Eerror:add () takes exactly 2 arguments (3 given) >>> map (Add, ' zhoujy ', ' Python ', ' testop ') [' zPt ', ' Hye ', ' ots ', ' u HT ', ' Joo ', ' YNP ']
Python Filter,map