python advantage of the power of python to learn through a piece of code

In her spare time at night I turned a bit random blog, see https://www.jianshu.com/p/69bf0ed0b5cc author mentions a piece of code, just started feeling nothing to see, after careful in-depth caught my attention. Which uses python simplest grammar, indeed produces the most magical effect, the code of the world's amazing! First posted at the source of it
1. What is a variable parameter, what is the key parameter
2, what basic python syntax
3, Why this code can get my attention

```python
def transfer_kwargs(*args):
kwargs = {}
for arg in args:
k, v = map(lambda x: x.strip(), arg.split('.', 1))
if '.' in v:
item = kwargs.setdefault(k, {}) # step1
values = v.split('.')
for j in values[:-2]:
item = item.setdefault(j, {}) # step2
item[values[-2]] = values[-1] # step3
else:
kwargs.update({k: v})
print(kwargs)
if __name__ == '__main__':
info1 = '1.2.3.4.5'
info2 = 'a.b.c.d.f'
transfer_kwargs(info1, info2)
输出:
>>>{'1': {'2': {'3': {'4': '5'}}}, 'a': {'b': {'c': {'d': 'f'}}}}
```

  


This code total of 13 lines of code, really realize the complex functions, the simple complicated character, of course, there are other ways to achieve this functionality, a summary of this analysis this function:
### 1. What is varying parameter, what keyword arguments
* args is a variable parameter, args is a tuple received; variable parameters into parameters using the plurality of the reference variable can. If we can run this function

```python
if __name__ == '__main__':
info1 = '1.2.3.4.5'
info2 = 'a.b.c.d.f'
info3 = 'e.f.g.h.i.j.k'
info4 = 'a1.b1.c1.d1.f1'
transfer_kwargs(info1, info2,info3, info4)
输出:
>>>{'a': {'b': {'c': {'d': 'f'}}}, '1': {'2': {'3': {'4': '5'}}}, 'a1': {'b1': {'c1': {'d1': 'f1'}}}, 'e': {'f': {'g': {'h': {'i': {'j': 'k'}}}}}}
```

  


Speaking of variable parameters, not to mention the keyword arguments; ** kwargs is keyword arguments, kwargs received a dict, the reference content can achieve the expansion, plus a variable parameter = keyword argument to the Senate universal parameters, here no longer tired.
### 2. What is the basis of the use of python syntax
#### 2.1 the Map (function, Iterable, ...)
the Map () will do the mapping function in accordance with the specified sequence provided.
The first parameter argument function to call the function function of each element in the sequence, each time the function returns a new list of function return values. Examples are as follows:

Python `` ` 
>>> DEF Square (X): calculate the number of squares # 
... return ** X 2 
... 
>>> Map (Square, [1,2,3,4,5]) # Calculation List the square of each element 
[1, 4,. 9, 16, 25] 
>>> Map (lambda X: X ** 2, [1, 2,. 3, 4,. 5]) using lambda # anonymous function 
[1, 4, 9, 16, 25] 

# two lists, a data list by adding the same position 
>>> map (lambda x, y: x + y, [1, 3, 5, 7, 9], [2 , 4, 6, 8, 10]) 
[3, 7, 11, 15, 19] 
`` `

  


2.2 lambda #### [arg1 [, arg2, ..... argn]]: expression The
Python anonymous functions, just a lambda expression, function body is much simpler than def; subject lambda is an expression, not a code block. You can only packaged in a lambda expression into the limited logic; lambda function has its own namespace, and can not be accessed outside its own list of parameters or global namespace parameters; although lambda function looks only write one line, but not equal to C or C ++ inline functions, which aims not occupy a small stack memory when calling the function to increase the efficiency, examples are as follows:

Python `` ` 
# / usr / bin / Python! 
UTF-. 8 - - *: # - - Coding * 

# Function Description Writable 
; + arg1 arg2: = sum the lambda arg1, arg2 

# call the sum function 
after print (" sum values: ", SUM (10, 20 is)) 
Print (" the added value: ", sum (20, 20 )) 
output: 
the value obtained by adding: 30 
the added value: 40 
`` `

  


2.3 str.strip #### ([chars])
the Python Strip () method for removing head and tail of the specified character string (line feed spaces or default) or character sequence; delete only the beginning or end of the method character, the character can not remove the intermediate portion, examples are as follows:

Python `` ` 
! # / usr / bin / Python 
# - * - Coding: UTF-. 8 - * - 

STR =" 00000003210Runoob01230000000 "; 
Print str.strip ( '0'); removing the first and last characters # 0 


str2 =" Runoob " ; # removing both spaces 
print (str2.strip ()); 
output: 
3210Runoob0123 
Runoob 
`` `

  


2.4 str.split #### (STR = "", num = string.count (STR)).
The Python Split () specified by slicing string delimiter, if num parameter value is specified, then the partition num + 1 sub-string. Examples are as follows:

`` Python ` 
! # / usr / bin / Python 
# - * - Coding: UTF-8 - * - 

TXT =" Google Taobao # # # Runoob Facebook " 

# 1 as the second argument and returns a list of two parameters 
x = txt.split ( "#",. 1) 

Print (X) 
output: 
[ 'the Google', 'Runoob # # Taobao Facebook'] 
`` `

  


2.5 dict.setdefault #### (Key, default = None)
the Python similar setdefault dictionary () function and the get () method, if the key does not exist in the dictionary, and the key value will be added to the default value; two ways What difference does it make, look at examples:

Python `` ` 
IF the __name__ == '__main__': 
Info5 = { 'Age': 18 is, 'name': 'Jack'} 
info6 = { 'Age': 18 is, 'name': 'Jack'} 
Print (Info5. get ( "sex", 'M')) 
Print (info6.setdefault ( "Sex", 'M')) 
Print (Info5) 
Print (info6) 
above example output is: 
M 
M 
{ 'age': 18, ' name ':' Jack '} 
{' Age ': 18 is,' name ':' Jack ',' Sex ':' M '} 
`

  


By way of example can be found dict.setdefault (key, default = None) taken using a key value does not exist (the return value is the default key and the new key stored in a dictionary)
#### 2.6 values [: - 2]
values [start: end: sTEP], wherein start: start index, starting from 0, -1 indicating the end; end: end index; step: step, end-start, the step is positive, to the left the right values. Step is negative, the reverse value. Note sliced end result does not contain an index that does not include the last one, -1 is the last position of the index list.
values [: - 2] 0 is the default starting position, in steps of 1, the end of the penultimate index characters. Examples are as follows:

` 
IF the __name__ ==" __main__ ": 
A = [1,2,3,4,5] 
Print (A [: - 2]) 
The output is: 
[1, 2, 3] 
` ``

  


### 3, Why this code can get my attention
the whole code is mainly string some order to do a little nesting process, such as the effect of:

`` ` 
IF the __name__ == '__main__': 
the INFO1 = '1.2.3.4.5' 
INF02 = 'ABCDF' 
transfer_kwargs (the INFO1, INF02) 
output: 
{ '1': { '2': { '3': { '. 4': '. 5'}}}, 'A': { 'B': { 'C': { 'D': 'F'}}}} 
`` ` 
vivo function of a string of sealing codes, item [ values [-2]] = values [ -1], the removed result code is 

`` ` 
{ '. 1': { '2': { '. 3': {}}}, 'a': { ' B ': {' C ': {}}}} 
`` `

  

In other words the rest of the main body functions implemented nested functions, traverse the list (excluding the last value, this value is used to process the rearmost sealing of the dictionary building 4 or the value of c). This simple nested, so that the value at the beginning of each dictionary key corresponding to the {}. Up to 4 and c is a value corresponding to the end of the 5 and d.

```
for j in values[:-2]:
item = item.setdefault(j, {})
```

  


At this point the analysis I believe we will be able to read the code, not too tired out after the analysis of this code, I find the following points so as to attract my key:
a simple syntax 1 python can achieve a number of complex operations, and a number of simple grammar mixing can achieve wonderful results. As referred to herein function.
2 the entire section of code without any redundancy, through the bad mixed with statements, conditional statements right achieved complex functions.
3 extend some basic knowledge of grammar item.setdefault (j, {}) This method is the first time I saw the perfect solution to get defects in grammar

 

 

 

 


python code, by simple and complex
basic grammar reference example 2 from [novice tutorial] (https://www.runoob.com/python)

Guess you like

Origin www.cnblogs.com/pujenyuan/p/12038953.html