Python Six musketeers (anonymous and built-in functions)

Source: Internet
Author: User
Tags iterable

I. Anonymous function lambda

1.lambda is just an expression, and the function body is much simpler than def.

The body of the 2.LAMBDA is an expression, not a block of code. Can only encapsulate a finite amount of logic in a lambda expression.

>>> def add (A, B):
... return A+b
...
>>> Add (1,4)
5
>>>
>>> Lambda x:x+2
<function <lambda> at 0x00000273c937b8c8> #函数
>>>
>>> A=lambda X,y:x+y
>>> A (2,6)
8

>>> f = [lambda x:x*i for I in range (4)]
>>> F[1] (1)
3
>>> f1 = [Lambda i=i:i*i for I in range (4)]
>>> F1[3] ()
9

Two.filter()函数

The filter () function is a useful high-order function built into Python, and the filter () function receives a function f and a list, which is the function f to judge each element

Returns TRUE or False,filter () automatically filters out non-conforming elements based on the result of the decision, returning a new list that is composed of qualifying elements.

For example, in a list, delete even numbers, keep only odd numbers, and you can write:

def   is_odd   (n):  return n%  2 = =  1filter (is_odd, [ 1,  2,  < Span style= "font-size:14px" >4,  5,  6,   9,  10,  15])  
Results: [1, 5, 9, 15]

Once you've learned the lambda function, you can do it one line
>>> list(filter(lambda x:x%2, [1, 2, 4, 5, 6, 9, 10, 15]))
[1, 5, 9, 15]
注意:python3 起,filter 函数返回的对象从列表改为 filter object(迭代器),
想要使用的话加上list(),将迭代器转换成列表,例如:利用filter(),可以完成很多有用的功能,删除 None 或者空字符串:

>>> def not_empty(s):
...     return s and s.strip()
...
>>> filter(not_empty, [‘A‘, ‘‘, ‘B‘, None, ‘C‘, ‘  ‘])
<filter object at 0x0000020833998AC8>
>>>
>>> list(filter(not_empty, [‘A‘, ‘‘, ‘B‘, None, ‘C‘, ‘  ‘]))
[‘A‘, ‘B‘, ‘C‘]

The Python Strip () method removes the character specified by the string's Kinsoku (by default, a space or line break) or a sequence of characters.

Note: This method can only delete characters at the beginning or end, and cannot delete the middle part.

Three. Map () function

Map () maps the specified sequence according to the provided function.
The first parameter function calls a function function with each element in the parameter sequence, returning a new list containing the return value of each function.

Map (function, iterable, ...)

      • function– function, with two parameters
      • iterable– one or more sequences
      • Returns the result as a list
>>> def ABC (A, B, c): 
...     return a * 10000 + b*100 + C
...
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>> > Map (ABC,LIST1,LIST2,LIST3)
<map object at 0x0000023e269a8be0>
>>> list (map Abc,list1, LIST2,LIST3))
[114477, 225588, 336699]

list (Map (Lambda x:x**2, Range (5))
[0, 1, 4, 9, +]

Four. Reduce () function
the reduce () function receives a parameter similar to map (), a function f, a list , but behaves and Unlike map (),
Reduce () The function f passed in must receives two parameters , and reduce () calls function f repeatedly on each element of the list and returns the final result value.
defAdd (x, y):      return x + y >>> reduce(add, [1, 3, 5, 7, 9])
25

When you call reduce (f, [1, 3, 5, 7, 9]) , the Reduce function calculates the following:

先计算头两个元素:f( 1 , 3 ),结果为 4 再把结果和第 3 个元素计算:f( 4 , 5 ),结果为 9 再把结果和第 4 个元素计算:f( 9 , 7 ),结果为 16 再把结果和第 5 个元素计算:f( 16 , 9 ),结果为 25 由于没有更多的元素了,计算结束,返回结果 25 Five. sectioning a=[1,2,3,4,5,6,7,8,9]
>>>
>>> A[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>
>>> A[::4] #步长为四
[1, 5, 9] six. Derivation list [expression for variable in list] or [expression for variable in list if condition]For example, suppose we want to create a list of square numbers, such as:>>> squares = []
>>> for x in range (10):
... squares.append (x**2)
...
>>> Print (squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>We can also get the same list in the following way:>>> squares = [x**2 for x in range (10)]
>>> [x**2 for X in range (10)]
[0, 1, 4, 9, +,-The following derivation list is the sum of the number of keys in the dictionary for integer type >>> [key for key in {1: ' A ', 2: ' B ', ' A ': 3} If Isinstance (Key,int)]
[1, 2]
>>> sum ([key for key in {1: ' A ', 2: ' B ', ' A ': 3} If Isinstance (Key,int)])
3
 


Python Six musketeers (anonymous and built-in functions)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.