This is because our cv teacher asked us to experience Huawei's AI Gallery. We have experienced a similar course before - the "basic operation" of paper clip (jibencaozuo.com). I personally feel it's good. Today, let's try Huawei's learning course.
1, Fundamentals of Python Programming
1.Print syntax
print("XDU-ldx") #Print the words of Xidian Li daixun
str = 'H U A W E I' for i in str: print (i) # Auto wrap after output #str means to enter a string # i does not exist in the string, so it is printed until the end of the character for j in str: print (j,end='') # Continue to output the next character without line break after output
Examples are as follows:
# Import Toolkit import sys # Import sys module print(sys.platform) # Printing system platform
2. Numerical value
print(True + False) # Output 1. True defaults to 1 and False to 0 print(True or False) # Output True, keyword or performs the or operation print(5 // 2) # output 2, / / is the rounding operator print(5%2) # Output 1,% is the remainder operator print(3**2) # Output 9, * * indicates power operation print(5+1.6) # Output 6.6, the high-precision type is taken as the result by default when adding numbers of different precision types
3. String
S = 'python' # Assign python to variable S # len(obj): returns the length of the object print(len(S)) # Output 6 print(S[0], S[1], S[-1]) # Output pyn and get the elements by index print(S + '1', S*2) # Output Python 1 Python: merge and repeat
4. List: the list in python is a powerful collection, which is represented by brackets. The data type of the list can be different, and the list can be included in the list.
for i in enumerate(animals): print(i) # An index consisting of an element subscript and an element #Output: (0, cat) # (1, dog) # (2, monkey) #List derivation squares = [x*2 for x in animals] # Batch generate a list of elements that meet the rules print(squares) #['catcat ', 'dogdog ', 'monkeymonkey '] list1 = [12, 45, 32, 55] # list.sort(cmp=None, key=None, reverse=False): cmp is an optional parameter. If this parameter is specified, the method of this parameter will be used for sorting. Key is the element used for comparison. Reverse is the sort rule and False is ascending. list1.sort() # Sort the list print(list1) # Output [12, 32, 45, 55] # list.reverse(): reverse the elements in the list. list1.reverse() # Invert the list print(list1) # Output [55, 45, 32, 12]
Python enumerate() function
It is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop (starting from 0).
5. Tuples: Python tuples are similar to lists, except that tuple elements cannot be modified. Tuples use parentheses and lists use square brackets.
T=(1, 2, 3) #Create tuple print(T + (4, 5)) #Tuple merging, output: (1, 2, 3, 4, 5) t=(42, ) #A tuple with only one element, as distinguished from a number tuple1 = (12, 45, 32, 55, [1, 0, 3]) # Create Yuanzu tuple1[0] = "good" # Program exception, immutability of tuples tuple1[4][0] = 2 # Variable elements in tuples can become print(tuple1) # (12, 45, 32, 55, [2, 0, 3])
6. Dictionary: a dictionary is an unordered collection of data used to store data values. Unlike other data types that treat only a single value as an item, dictionaries have key value pairs. Keys and values in the dictionary are separated by colon ":", key value pairs are separated by comma "," and all key value pairs are enclosed by curly brackets "{}".
# Three assignment operations of dictionary x = {'food':'Spam', 'quantity':4, 'color':'pink'} X =dict(food='Spam', quantity=4, color='pink') x = dict([("food", "Spam"),("b", "2"), ("color", "pink")]) # dict.copy(): copy data d =x.copy() d['color'] = 'red' print(x) # {'food':'Spam','quantity':4,'color':'pink'} print(d) # {'food':'Spam','quantity':4,'color':'red'} #Element access print(d.get('name')) # Output None print(d.get('name', 'Key value does not exist!')) # The output key value does not exist print(d.keys()) # Output dict_keys(['food', 'quantity', 'color']) print(d.values()) # Output dict_values(['Spam', 4, 'pink']) print(d.items()) # Output dict_items([('food', 'Spam'), ('quantity', 4), ('color', 'pink')]) d.clear() # Clear all data in the dictionary print(d) # Output {} del(d) # Delete dictionary print(d) # Program exception, prompt "d" undefined
7. Assembly:
sample_set = {'Prince', 'Techs'} print('Data' in sample_set) # Output False. In is used to check whether an element exists in the collection # set.add(obj): adds an element to the collection. If the added element already exists in the collection, no operation will be performed. sample_set.add('Data') # Adds the element Data to the collection print(sample_set) # Output {Prince ',' techs', 'data'} print(len(sample_set)) # Output 3. The len() function returns the number of collection elements # set.remove(obj): removes the specified element from the collection. sample_set.remove('Data') # Delete element Data print(sample_set) # {'Prince', 'Techs'} list2 = [1, 3, 1, 5, 3] print(list(set(list2))) # Output [1,3,5], and use the uniqueness of set elements for list de duplication sample_set = frozenset(sample_set) # The immutable set frozenset() function returns a frozen set. After freezing, the set cannot add or delete any elements.
8. Deep copy and shallow copy: deep copy is to copy the whole object to be copied and store it in a newly opened space; Shallow copy refers to copying a copy of the object to be copied, but not its internal child objects, but direct reference, which is similar to adding a link
import copy Dict1 = { 'name':'lee', 'age':89, 'num':[1,2,8]} # New dictionary Dict_copy = Dict1.copy() # Shallow copy Dict_dcopy = copy.deepcopy(Dict1) # Deep copy Dict1['num'][1] = 6 # Modify the value of the nested list in the original data print('Dict1:' + str(Dict1), ' Dict_copy:' +str(Dict_copy),' Dict_dcopy:' + str(Dict_dcopy))
9. if judgment statement:
#Judge according to the score entered # input(): used to receive input. score = input("Please enter your score") # The input function receives input as a string score = float(score) # Convert scores to numeric type # Try:... except Exception:... Is a statement used to catch exceptions in Python. If an error occurs in the statement in try, the statement in except will be executed. try: if 100 >= score >= 90: # Judge whether the entered value is greater than the grade score print("excellent") # Output level after meeting the conditions elif 90 > score >= 80: print("good") elif 80 > score > 0: print("in") else: print("difference") except Exception: print("Please enter the correct score")
10. Circular statement:
#while Loop i = 0 # New i variable while i < 9: # Set cycle conditions i += 1 # Each cycle i increases by 1 if i == 3: # Judge whether the conditions are met print("Jump out of this cycle") continue # continue jumps out of the current loop if i == 5: print("Jump out of the current big loop") break # Jump out of the current big loop print(i)
11. Function
def fibs(num): # Position parameters result = [0, 1] # A new list stores the values of a series for i in range(2, num): # Cycle num-2 times a = result[i - 1] + result[i - 2] result.append(a) # Append value to list return result # Return to list print(fibs(5)) # Output: [0, 1, 1, 2, 3]
12. Class: if multiple functions need to use the same set of data repeatedly, it will be convenient to use class for processing
class Greeter(object): # Create a new class and inherit object def __init__(self, name): # Initialization class self.name = name # Create an instance variable # Example method def greet(self, loud=False): if loud: print('HELLO, %s!' % self.name.upper()) else: print('Hello, %s' % self.name) g = Greeter('Fred') # Create an instance of the Greeter class g.greet() # Hello,Fred calls the instance method with default parameters g.greet(loud = True) # HELLO, FRED call instance method, custom parameters
13. Multithreading: Thread, also known as lightweight process, is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operation unit in the process. A Thread does not own system resources, but only a few resources that are essential for running, but it can share all the resources owned by the process with other threads belonging to the same process. One Thread can create and undo another Thread, and multiple threads in the same process can execute concurrently
import threading #Import threading module from time import sleep, ctime #Import time module def work1(): #Definition method for i in range(3): print("work1 Executing...%d"%i) sleep(1) def work2(): #Definition method for i in range(3): print("work2 Executing...%d"%i) sleep(1) if __name__ == '__main__': print('---start---:%s'%ctime()) t1 = threading.Thread(target=work1)# Thread 1 t2 = threading.Thread(target=work2)# Thread 2 # Start thread t1.start() t2.start() sleep(5) print('---end---:%s'%ctime())
import threading import time g_num = 0 def test1(num): global g_num # Use global variables for i in range(num): mutex.acquire() # Lock g_num += 1 mutex.release() # Unlock print("---test1---g_num=%d"%g_num) def test2(num): global g_num for i in range(num): mutex.acquire() # Lock g_num += 1 mutex.release() # Unlock print("---test2---g_num=%d"%g_num) # Create a mutex # It is unlocked by default. You can view the result of resource contention after deleting the lock mutex = threading.Lock() # Create 2 threads and let them each pair g_num plus 1000000 times p1 = threading.Thread(target=test1, args=(1000000,)) p1.start() p2 = threading.Thread(target=test2, args=(1000000,)) p2.start() # Wait for the calculation to complete time.sleep(5) print("2 The final result of multiple threads operating on the same global variable is:%s" % g_num)
14. Regular expression: regular expression is a powerful string processing tool. Almost any operation on string can be completed by regular expression.
import re phone = "2019-0101-000 # This is a phone number“ # Remove Python comments from string num = re.sub(r'#.*$', "", phone) print("The phone number is: ", num) # Delete non numeric (-) strings num = re.sub(r'\D', "", phone) print("The phone number is : ", num)
15. Magic methods: magic methods are built-in python methods, which do not need to be called actively. They exist to call the python interpreter. Almost every magic method has a corresponding built-in function or operator. When we use these functions or operators on this object, we will call the corresponding magic methods in the class, It can be understood as rewriting these python built-in functions.
class Dog(object): #Define a class def __init__(self, name): self.name = name print("Puppy:%s"%(self.name)) dog = Dog("dog")