“This is the 12th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
First, the use of functions:
Function scope: if a variable in a function has the same name as a global variable, the global variable name will be overwritten. That is, changes to this variable will not change the global variable. However, if used directly, global variables are used. Also, if you want to modify a global variable, specify the global variable: global A
2. Xrange uses the same as range, but is more efficient because it does not create lists in memory. So, it can only be used for loops.
3. If the function has no return statement, it returns None.
4, on the function input judgment: if this is empty, an exception may occur. When an exception occurs, there may be a situation where a task is not progressing halfway through and may cause a memory leak. How can this problem be solved? In C’s case, it is possible to make a judgment for each input parameter, but it is too cumbersome. And look at a lot of open source pages that don’t do this. Is there a better way? Another way to think about it is to make sure it is not null before calling. Take a look at how open source code works. Especially openstack.
5, variable input parameter: *args, **kwargs means variable input parameter.
Def funtest(a, b, c): def fun2(*args, **kwargs): def fun2(*args, **kwargs) fun2(1,2,3)Copy the code
It can also be defined like this:
fun2(a, *args, **kwargs)
Copy the code
How to resolve the value of a variable parameter from a variable parameter?
Add print to fun2: you can see that args is a tuple and kwargs is a dictionary.
Analysis: calling fun2(1,2,3) assigns a to a,2 to the tuple args, and {‘ c ‘=3} to kwargs.
The order of args and Kwargs cannot be reversed.
Both args and kwargs may have values at the same time. Thus, to get the specified input parameter, first look for args and then look for kwargs based on the string.
How to build a tuple or dictionary that is passed to a function as an argument?
Def funtest (a, b, c) : print (a, b, c) d = {' a ', 1, 'b' : 2, 'c' : 3} l = (1, 2, 3) funtest (* l) funtest (d) * *Copy the code
* and ** do this in Python. It’ll be flexible.
***** and ** can also appear alone. However, if both occur, * must precede **.
6, default parameters or optional parameters, parameter order: when called, you can specify which of the default parameters to fill.
def funtest(a, b=1, c=2):
print(a, b, c)
funtest(1, c=5, b=6)
Copy the code
Def funtest(a, b, c) can also be called as funtest(1, c=5, b=6).
Parameter groups: *args, **kwargs is the parameter group, with tuples and dictionaries to bring in the generation. This feature facilitates more dynamic code generation.
8. Variable length parameters:
If one of the arguments to a function is a tuple, we can do this:
Def fun(a, (b, c)): print(a, b, c) fun(1, 2)Copy the code
For callbacks, you can use closures, generators, and the __call__ attribute of an object. Can encapsulate state.
Ii. Use of closures:
A closure is an object that packages together the statements that make up a function and its execution environment.
Closures prior to 2.7 do not support the keyword nonlocal. Only supported after 3.0. Therefore, closures prior to 2.7 cannot use nonlocal.
3. So that he cannot make changes to variables in the execution environment.
Iii. Use of dictionary:
1. Dictionary deletion: Using del Dict [k] directly may raise an exception; First, it is inefficient to judge whether K exists. Using exceptions makes the program structure look bad. A good method is pop(k, default V). This removes one k term and returns. Return the default v if none exists. If the default value is not added, an exception is thrown.
2. Fetching the value of a dictionary directly with a dictionary subscript may cause a conflict. The get method does not, and returns None if it does not exist. Alternatively, you can set defaults that do not exist.
Print “value is %(key)s” % kvdict
The items method returns a list of tuples, the first of which is a key and the second is a value. Better use of the method.
Iteritems: Returns an iterator. If you want to iterate over the dictionary, iterItems is a little more efficient than items.
Iterkeys returns an iterator of key. Keys returns a list of keys.
Values returns a list of values. Itervalues returns a vlaue iterator
8. Popitem pops (and deletes) a random item, which is helpful if you want to process all elements and delete all elements. However, if no element is available, an exception is thrown.
Viewitems, ViewKeys, viewValues: These three functions return a view object. This is like a view. Represents the list of (key, value) pairs, the list of keys, and the list of values. One advantage is that if the dictionary changes, the View changes in sync. The dictionary is not allowed to change during iteration, otherwise an exception will be reported.
Int, STR, tuple (int, STR, tuple); For custom objects, the address of the object is used as the key value. This has not been fully proved. Object comparison, built-in types, because they override the default object __eq__ and so can compare content. Custom objects are not overridden, so they may be compared differently. What is the default comparison of object? I’m not sure yet, but I’ll fill in later. It may be the address (or the unique identity of the object) rather than the content of the object. When it comes to dictionaries, it doesn’t use a pure comparison, but rather a __hash__, which returns a hash value from which the dictionary only spreads objects.
Iv. Use of lists:
1, list deletion: do not delete linked lists in the traversal process, which will get unpredictable consequences. You can use list filtering to get a new list.
2. List filtering:
Def filterFun(node):# This function does two things.
node.cycleCount = node.cycleCount - 1
return node.cycleCount < 0
timeoutList = filter(filterFun, timerList)
Copy the code
Execute filterFun on each node in the timerList and form a new list of true items based on the results returned by filterFun.
3, kvlist = map(lambda x:x.strip(), kvlist). Kvlist = map(lambda x,y:x+y, [1,2,3], [4,5,6]) kvlist = map(lambda x,y:x+y, [1, 3], [4,5,6])
If the function is None, it is equivalent to zip:
Zip ([1, 2, 3], [4 and 6])
[(1, 4), (2, 5), (3, 6)]
L = [node for node in xrange(5) if node-3 < 0]: this method can replace filters and maps to some extent.
Generator expression definition:
[expr for iter_var in iterable if cond_expr]
L = [2 for x in xrange(5)]# produces a list of 5 2’s
- print(reduce(lambda x,y: x*y, [2 for x in xrange(38)]))
The above statement evaluates 2 to the 38th power. It uses the binary function reduce. Its first call takes the first and second elements as arguments, then uses their result as x, the new element as y, and finally returns the value.
Alternatively, it can be used to get a list of 38 twos: [2] * 38. This is probably a little bit more readable.
5. Enumerate: Returns the index and node of a list.
for index, node in enumerate(timerList):
if timerId == node.timerId and timerEvent == node.timerEvent:
del timerList[index]
Table fragmentation: [1,2,3,4], L [1:-1] indicates the index from 1 to the last, excluding the last. If you want to go from a position to the end, you should: [1:]
7, L [I :j:k]: represents slice, from I to j, step length is K.
8, l[I :j]: indicates from I to j, excluding index j.