Getting started with Python: three tips on Data Structure
This is the first article on Python. It mainly introduces three tips on data structure.
Sort:
Use the sorted function to sort data.
The sorted function sorts the elements in each list in the order of length, size, and English letters. This function is often used in data presentation. It is very important that the sorted function does not change the List itself, which is equivalent to copying the list and sorting it.
1 list = [,] 2 print (sorted (list) 3 # The number is sorted from small to large by default 4 print (sorted (list, reverse = True )) 5 # reverse, sort 6 print (list) in reverse order 7 # The sorted function does not change the original list
Derivation (analytical expression of the list ):
Add the 10 elements to the list. See the following two methods.
1 # common syntax 2 a = [] 3 for I in range (): 4. append (I) 5 # append method is used to add a new object 6 print (a) 7 8 9 at the end of the list # derivation formula 10 B = [I for I in range ()] 11 print (B
First, create an empty list and install it one by one. The second is the derivation, Which is concise and clear. Of course, the derivation method is much more efficient than the common method. We can estimate the time:
1 import time 2 3 # general syntax 4 a = [] 5 t1 = time. clock () 6 for I in range (1, 20 000): 7. append (I) 8 print (time. clock ()-t1) 9 10 11 # derivation 12 t2 = time. clock () 13 B = [I for I in range (1, 20 000)] 14 print (time. clock ()-t2)
Obtain the index of an element in the loop list:
For example, in the alphabet letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G, obtain the position of each element.
1 letters = ['A', 'B', 'C', 'D', 'E', 'E', 'F', 'G'] 2 for num, letter in enumerate (letters): 3 # The enumerate function is used to traverse the elements in the sequence and Their subscript 4 print (letter, 'in the', num + 1, 'location ')
Later, I started to access classes in Python.
Operating Environment: Python version, 3.6; PyCharm version, 2016.2; Computer: Mac
----- End -----
Author: du wangdan, Public Account: du wangdan, Internet product manager.