Python basis: cycling conditions

Conditional statements

  In addition boolean values, preferably conditional dominant
  
if i != 0:
...

  Rather than just write the variable name:

if i:
...

For Loop and While Loop

  • Generally speaking, if you just traversed a known collection, to find elements to meet the conditions, and the appropriate action, then use a for loop is more concise.
  But if you need to meet certain conditions before, he kept repeating certain operations, and there is no specific set of needs to traverse, then the general will use a while loop.
  • range () function is directly written in C language, calling it very fast.
  And while loop "i + = 1" This operation is to obtain an indirect call C language bottom by Python interpreter; and this simple operation, also involves the creation and deletion of objects (since i is an integer, is immutable , i + = 1 corresponds to i = new int (i + 1)).
  So, obviously, for superior efficiency of the cycle.

Multiplexing cycle conditions

  Example: Given two lists attributes and values, required values ​​for each group of sub-list value, and outputs a list of the attributes in the dictionary corresponding to the key consisting of:
[{'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}, 
{'name': 'mike', 'dob': '1999-01-01', 'gender': 'male'}, 
{'name': 'nancy', 'dob': '2001-02-01', 'gender': 'female'}]

  Multiple lines of code:

import copy
attributes = ['name', 'dob', 'gender']
values = [
    ['jason', '2000-01-01', 'male'], 
    ['mike', '1999-01-01', 'male'],
    ['nancy', '2001-02-01', ' FEMALE ' ] 
]
 
l_except = [] 
D = {}
 for value in values:
     # method 
    # for index, V in the enumerate (value): 
        # D [Attributes [index]] = V 
    # Method II 
    D = dict ( ZIP (Attributes, value)) 

    l_except.append (D) 
# d.clear () # Notably list, dict is passed by reference, if the call sentence of the sentence will be [{}, {}, {}] 
           # can pass learn copy target l_except.append (copy.deepcopy (d)) with copy.deepcopy 
Print (l_except)

  Processing line of code:

l_except = [{arrt: v[index] for index, arrt in enumerate(attributes)}for v in values]
print(l_except)
# or
l_except = [dict(zip(attributes,v)) for v in values]
print(l_except)

reference:

  Geek Time "Python core technology and practical"

 

 

Guess you like

Origin www.cnblogs.com/xiaoguanqiu/p/10930197.html