Python core technology and real - five | Conditions circulation

Earlier, we learned the basic type of data structure a series of Python lists, tuples, dictionaries, collections and strings, etc., we need to put a string together under one of the basic data, which we use to talk about today things - "conditions and circulation."

A. Conditional statement

  Usage is very simple conditional statements, such as we want to represent y = | x | this function, then the corresponding code is this (simplified code is not considered abnormal, the latter, too)

#y = |x|
x = float(input('>>>'))
if x < 0:
    y = -x
else:
    y = x

  Note that different Python and other languages ​​in the conditional statement is not bracketed end of the sentence but also by a colon. This is a Python-specific syntax.

if (x<0)

  Python is not supported by a switch statement, when multiple conditions are judged, we use else if realized. When the usage of Python elif, is probably such a thought

if case1:
    do 1
elif case2:
    do 2
elif case3
    do 3
else:
    do n

  Where if statements can be used alone, but must be elif and else and if necessary use.

  Sometimes to simplify the code, the determination conditions may be omitted, so can be used:

= S ' the this IS A String ' 
L = [ ' A ' , ' B ' , ' C ' ] 
I = 123
 IF S:
     Print ( ' non-empty string ' )
 IF L:
     Print ( ' list is not empty ' )
 IF I: Print ( ' integers 0 ' )   # Note that the wording (in the same row) are also possible

Usage determination condition is omitted below about several

type of data in conclusion
String Empty string parsing is False, the rest is Ture
Int 0 resolves to False, the rest is Ture
Bool Ture Ture is
list/tuple/dict/set iterable is empty False, the rest are True
Object None to False, the rest is True

  However, in practice, in addition to Bool type of data to determine the best conditions as a dominant, that is best to write out the condition determination to create good conditions for the maintenance and reading others later. For example it is determined whether a number 0

IF I:
     Print ( ' the number is 0 ' ) 

IF I == 0:
     Print ( ' the number is 0 ' )

  The following syntax is more obvious and easy to read. In particular, a bunch of code segments, wants to understand them is not easy.

II. Loops

  Loop through the elements is the essence of the collection. Python is generally accomplished by circulating while and for.

  often used for loop iteration traversal of the object may be

= {D ' name ' : ' Jack ' ,
       ' Age ' : 20 is ,
       ' Job ' : ' HR ' }
 for Key in D:
     Print (Key)       # traversing a dictionary Key 
for value in d.values ():
     Print ( value)     # traversing dictionary value 
for K, V in d.items ():
     Print ( ' Key: {}, value: {} ' .format (K, V))   #Traversal key-value pairs

  Here is an example of the dictionary, because the dictionary itself only key is iterative, if we want to traverse its value or key-value pair, it is necessary to use the built-in dictionary function value () or items () to achieve. In some cases there may also be () function to get indexed by the range, go through the elements in the collection

l = ['a','b','c','d','e','f','g']
for index in range(0,len(l)):
    if index<3:
        print(index,l[index])

  When we also need to index and elements, there is a more concise way: the use of built-in functions enumera Python (). It is used to traverse the collection, only to return each element, also returns to its corresponding index, the above code can be written as such

l = ['a','b','c','d','e','f','g']
for index,item in enumerate(l):
    if index < 5:
        print(item)

  In the loop, we also often used in conjunction with the continue and break. skip this section is to continue the current cycle, continue with the next iteration of the loop, and the break is completely out of the entire body of the loop. The appropriate combination of continue and break, make pure Guangxu more concise and easy to read. For example: There are two dictionaries, respectively, when the price of the product name and product name mapping to map the color list. If we want to find out the price of less than 1000, and the color is not red All product names and color combination, do not continue is this

name_price = {}
name_color = {}
for name,price in name_price.items():
    if price < 1000:
        if color in name_color:
            for color in name_color[name]:
                if color != 'red':
                    print('name:{},color:{}'.format(name,color))
        else:
            print('name:{},color:{}'.format(name,'None'))

And plus continue much simpler

name_price = {}
name_color = {}
for name,price in name_price:
    if price >= 1000:
        continue
    if name not in name_color:
        continue
    for color in name_color[name]:
        if color == 'red':
            continue
        print('name:{},color:{}'.format(name,color))

   Can be seen a first method for nested or if the layer 5 and the second method only 3 Continue adding nesting.

  Speaking in front of a for loop, in fact, for a while loop principle is the same, as long as the condition is satisfied, the operation is repeated inside the loop, known condition is no longer met, out of the loop body.

while contition:
    ...

  Many times for and while loops can be converted to each other, such as the above for loop through the list, can be done if the while loop.

l = ['a','b','c','d','e','f','g']
index = 0
while index<len(l):
    print(l[index])
    index +=1

  So these two uses what difference does it? If only traverse a known collection, to find elements to meet the conditions and the corresponding operations, then use a for loop is more concise. However, if desired stop before repeating a certain operation condition is satisfied, there is no specific need to traverse the set, then use the while loop is generally used. For example, if there is an interactive question and answer system, upon receiving the input information is the 'q' program exits. This time it is not normally the for loop.

while True:
    data = input('>>>')
    if data == 'q':
        print('stop')
        break
    else:
        print(data)

Three .for and efficiency while

  Efficiency of two kinds of cycles should be concerned about.

i = 0
while i < 1000000:
    i =+ 1

for i in range(0,1000000):
    pass

  These two cycles are equivalent, but since the range () function is directly written in C language, called very fast; and the while loop i + = 1 This operation is invoked by the underlying Python interpreter C directly language; and this operation involves the creation and deletion of objects (since i is an int, is immutable, i + = 1 corresponds to i = new (i +1) for the cycle so the efficiency will be higher.

IV. Conditions of reuse and recycling

  Sometimes the condition and will loop and a line operation, e.g.

#复写方法
expression1 if condition else expression2 for item in iterable
#分开写法
for item in iterable:
    if condition:
        expression1
    else:
        experssion2

  And if there is no else statement, you can write

experssion for item in iterable if condition

   For example, we want to draw such as f (x) = 2 | +5 FIG function, should the value of y corresponding to x calculated from the data points, then a single line of code can | x

x = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
y = [value*2+5 if value >0 else -value*2+5 for value in x]
print(y)

  Skilled, you will find that this approach is very convenient, but if the logic is more complicated when his party is difficult to understand, but also prone to error against others reading the code. Write code in the normal way is also a good selection and specification.

V. Questions

  Two lists of attributes and values, and the values ​​in the dictionary for each group of sub-list value, enter the attributes and the corresponding key, and returns a list consisting of dictionaries

attributes = ['name', 'dob', 'gender']
values = [['jason', '2000-01-01', 'male'], 
['mike', '1999-01-01', 'male'],
['nancy', '2001-02-01', 'female']
]

# expected outout:
[{'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}, 
{'name': 'mike', 'dob': '1999-01-01', 'gender': 'male'}, 
{'name': 'nancy', 'dob': '2001-02-01', 'gender': 'female'}]

 Try to complete in two ways: multiplex or branch:

out = []
for value in values:
    person = {}
    for index in range(len(value)):
        person[attributes[index]] = value[index]
    out.append(person)
print(out)

Standalone version:

out = [{attributes[i]: value[i] for i in range(len(attributes))} for value in values ]
print(out)

 

Guess you like

Origin www.cnblogs.com/yinsedeyinse/p/11156717.html