In RPA gracefully write Python code (b)

Connected in a gracefully written Python code (a) RPA in

6. The list of indexes show various operations


Python introduce negative integers as the array index, which is definitely a big hi Ben & Poor's move. Think about it, in C / C ++, you want the last element of the array, it must first obtain the array length, indexed after a cut, seriously affect the continuity of thought. The reason why the success of the Python language, I think, in which many factors, convenience, a list of actions that can not be ignored. Take a look:

>>> a = [0, 1, 2, 3, 4, 5]
>>> a[2:4]
[2, 3]
>>> a[3:]
[3, 4, 5]
>>> a[1:]
[1, 2, 3, 4, 5]
>>> a[:]
[0, 1, 2, 3, 4, 5]
>>> a[::2]
[0, 2, 4]
>>> a[1::2]
[1, 3, 5]
>>> a[-1]
5
>>> a[-2]
4
>>> a[1:-1]
[1, 2, 3, 4]
>>> a[::-1]
[5, 4, 3, 2, 1, 0]
```
If we say that you are familiar with these, too often, then the next this usage, you will feel amazing:
>>> a = [0, 1, 2, 3, 4, 5]
>>> b = ['a', 'b']
>>> a[2:2] = b
>>> a
[0, 1, 'a', 'b', 2, 3, 4, 5]
>>> a[3:6] = b
>>> a
[0, 1, 'a', 'a', 'b', 4, 5]

 

 

7. lambda function


lambda is an anonymous function, defined anonymous functions where the use of this function, less than elsewhere, so I do not need to give it a function name. The following is a summation of anonymous function has two input parameters, x and y, the function body is x + y, is omitted return keyword.

>>> the lambda the X-, the y-: the X-+ the y-
 <function < the lambda > AT 0x000001B2DE5BD598> 
>>> ( the lambda the X-, the y-: the X-+ the y-) (3, 4) # because the anonymous function has no name, use the time to use parentheses to group wrap it up

 


Anonymous functions generally not used alone, but in conjunction with other methods, or algorithms providing built determination condition other methods. For example, when using the sort function sorted to sort multidimensional array or dictionary, you can specify a collation.

>>> a = [{'name':'B', 'age':50}, {'name':'A', 'age':30}, {'name':'C', 'age':40}]
>>> sorted(a, key=lambda x:x['name']) # 按姓名排序
[{'name': 'A', 'age': 30}, {'name': 'B', 'age': 50}, {'name': 'C', 'age': 40}]
>>> sorted(a, key=lambda x:x['age']) # 按年龄排序
[{'name': 'A', 'age': 30}, {'name': 'C', 'age': 40}, {'name': 'B', 'age': 50}]

 

As another example of the array elements squared, this time with the map function:

>>> a = [1,2,3]
>>> for item in map(lambda x:x*x, a):
print(item, end=', ')

1, 4, 9, 

 

8. yield and generating and iterators


To understand yield, we must first understand the generator (generator). To understand the generator, get to know iterator (iterator).
Saying py2 era, range () returns a list, but if the range (10000000), it will consume a lot of memory resources, so, py2 has carried out a xrange () to solve this problem. py3 only retained xrange (), but writing range (). xrange () returns an iterator is, as it can be traversed like a list, but do not take up much memory. generator (generator) is a special iterator, can only be traversed once, traversing the end, it automatically disappears. In short, whether it is an iterator or generator, it is to avoid using the list, thus saving memory. So, how to get iterators and generators do?

ITER python built iterative function, for generating the iterator is used as follows:

>>> a = [1,2,3]
>>> a_iter = iter(a)
>>> a_iter
<list_iterator object at 0x000001B2DE434BA8>
>>> for i in a_iter:
print(i, end=', ')

1, 2, 3,

 

yield is used to construct the generator. For example, we write a function that returns a positive integer from 0 to a square of all integers, is the traditional writing this code:

>>> def get_square(n):
result = list()
for i in range(n):
result.append(pow(i,2))
return result

>>> print(get_square(5))
[0, 1, 4, 9, 16]

However, if the calculation of all integers less than 100 million square feet, the memory overhead of the function will be very large, which is the yield you can flourish:

def get_square(n):
for i in range(n):
yield(pow(i,2))

>>> a = get_square(5)
>>> a
<generator object get_square at 0x000001B2DE5CACF0>
>>> for i in a:
print(i, end=', ')

0, 1, 4, 9, 16,

If the traversal again, there will be no output.

9. decorator
Python provides a lot of weapons, decorator is one of the most powerful weapon for us. Decorator is very strong, I am here to try from the perspective of demand, with a simple example of how the decorator methods and manufacturing processes.

If we need to define a number of functions, each function when running this function to display the long run, there are many solutions. For example, you can read about each function before calling time stamp, after the end of each run function to read the time stamp, difference can; you can read the time stamp at the beginning and end of each function in the body, the final demand difference. However, these methods are not used decorator so simple and elegant. The following example illustrates this well.

>>> import time
>>> def timer(func):
def wrapper(*args,**kwds):
t0 = time.time()
func(*args,**kwds)
t1 = time.time()
print('耗时%0.3f'%(t1-t0,))
return wrapper

>>> @timer
def do_something(delay):
print('函数do_something开始')
time.sleep(delay)
print('函数do_something结束')


Do_something >>> (3 ) 
function do_something start 
function ends do_something 
takes 3. 077

 


timer () is defined by our decorator function, use the @ attach it before any function (such as do_something) the definition, it means a new definition of the function, as a function of the input parameters decorator. Run do_something () function, it can be understood as the implementation of a timer (do_something). Although the details of the complex, but not too much deviation so understandable and easier to grasp the manufacture and use decorators.

10. Using assertions assert


The so-called assertions, the statement is a Boolean value expression must be true for judgment, otherwise it will trigger the AssertionError. Strictly speaking, assert debugging tools, it should not be used in a production environment, but this does not affect our use assertions to achieve some specific functions, such as the format of the input parameters, the type of verification.

>>> DEF i_want_to_sleep (Delay):
 Assert (the isinstance (Delay, (int, a float))), ' the function arguments must be integers or floating point ' 
Print ( ' start sleeping ' ) 
the time.sleep (Delay) 
Print ( ' sleeping wake up ' )


 >>> i_want_to_sleep (1.1 ) 
began to sleep 
woke up
 >>> i_want_to_sleep (2 ) 
began to sleep 
woke up
 >>> i_want_to_sleep ( ' 2 ' ) 
Traceback (MOST recent Results Last Call): 
File " <pyshell # 247> " , Line 1,in <module>
i_want_to_sleep ( ' 2 ' ) 
File " <244 pyshell #> " , Line 2, in i_want_to_sleep
 Assert (the isinstance (Delay, (int, a float))), ' function argument must be integer or floating ' 
AssertionError with: function parameter must integer or floating point

  Free Trial: https://support.i-search.com.cn/

Guess you like

Origin www.cnblogs.com/isearch/p/11918472.html