Sep 3, 2018
Last updated
Last updated
前天学习Rabin-Karp之后没有自己看Tushar写的代码,今天一下,嗯?骚操作?注意到上一段代码有这样一个操作 for i, j in zip(str1, str2):
zip()
From the ,
zip
returns a list of tuples, where thei_th
tuple contains thei_th
element from each of the argument sequences or iterables. This is useful for iterating over two lists in parallel. For example, if I have two lists, I can get the first element of both lists, then the second element of both lists, then the third, etc.
If the lists are different lengths, zip
truncates to the length of the shortest list. Using map
with None
is similar to zip
except the results are padded with None
.
If I have a list of keys and a list of values, I can create a dictionary by passing the output of zip
to dict
.
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory. Let us get to it step by step
Firstly, a Nested Function is a function defined inside another function. It's very important to note that the nested functions can access the variables of the enclosing scope. However, at least in python, they are only read only. However, one can use the "nonlocal" keyword explicitly with these variables in order to modify them.
For example:
This works well as the 'data_transmitter' function can access the 'message'. To demonstrate the use of the "nonlocal" keyword, consider this
Without the nonlocal keyword, the output would be "3 9", however, with its usage, we get "3 3", that is the value of the "number" variable gets modified.
Now, how about we return the function object rather than calling the nested function within. (Remember that even functions are objects. (It's Python.))
And we call the function as follows:
Even though the execution of the "transmit_to_space()" was completed, the message was rather preserved. This technique by which the data is attached to some code even after end of those other original functions is called as closures in python
ADVANTAGE : Closures can avoid use of global variables and provides some form of data hiding.(Eg. When there are few methods in a class, use closures instead).
Also, Decorators in Python make extensive use of closures.