Dictionaries
A dictionary is an unordered variable sequence of "key value pairs". Each element in the dictionary is a "key value pair", including "key object" and "value object". You can quickly obtain, delete and update the corresponding "value object" through "key object".
In the list, we find the corresponding object by "subscript number". Find the corresponding "value object" through "key object" in the dictionary. "Key" is any immutable data, such as integer, floating point number, string and tuple. However, variable objects such as lists, dictionaries, and collections cannot be used as keys. And the "key" cannot be repeated
A typical dictionary definition form: (three "key value pairs" name is the key and zhangsan is the value)
a={'name':'zhangsan,'age':18,'job':'programmer'}
>>>a.get('name')
zhangsan
Dictionary creation
1. We can create dictionary objects through (), dict()
>>>a={'name':'zhangsan','age':18,'job':'programmer'} >>>a {'name': 'zhangsan', 'age': 18, 'job': 'programmer'} >>>b = dict(name='zhangsan',age=18) >>>b {'name': 'zhangsan', 'age': 18} >>>c=dict([('name','zhangsan'),('age',18)]) >>>c {'name': 'zhangsan', 'age': 18} >>>c={} #Empty dictionary object >>>d=dict() #Empty dictionary object
2. Create dictionary object through zip()
>>>k=['name','age','job'] #Key object collection >>>v=['gaoqi',18,'teacher'] #Value object collection >>>d=dict(zip(k,v)) >>>d {'name': 'gaoqi', 'age': 18, 'job': 'teacher'}
3. Create a dictionary #none with an empty value through fromkeys to indicate that the value is empty
>>>a=dict.fromkeys(['name','age','job']) >>>a {'name': None, 'age': None, 'job': None}
Access to dictionary elements
To test various access methods, a dictionary object is set here:
a={'name':'zhangsan','age':18,'job':'programmer'}
1. Obtain "value" through [key]. If the key does not exist, an exception is thrown
>>>a={'name':'zhangsan','age':18,'job':'programmer'} >>>a['name'] 'zhangsan' >>>a['age'] 18 >>>a['sex'] Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> a['sex'] KeyError: 'sex'
2. Get the "value" through the get () method. Recommended. The advantage is: if the specified key does not exist, return None; You can also specify the object returned by default when the key does not exist. It is recommended to use get() to get "value object"
>>>a.get('name') 'zhangsan' >>>a.get('ddd') >>>a {'name': 'zhangsan', 'age': 18, 'job': 'programmer'} >>>print(a.get('dddd')) None >>>a.get('ddd','non-existent') 'non-existent'
3. List all key value pairs
>>>a.items() >>>dict_items([('name', 'zhangsan'), ('age', 18), ('job', 'programmer')])
4. List all keys and all values
>>>a.keys() dict_keys(['name', 'age', 'job']) >>>a.values() dict_values(['zhangsan', 18, 'programmer'])
5. Number of len () key value pairs
>>>a={'name':'zhangsan','age':18} >>>len(a) 2
6. Check whether a "key" is in the dictionary
>>>a={'name':'zhangsan','age':18} >>>'name'in a True
Add, modify and delete dictionary elements
1. Add "key value pair" to the dictionary. If the "key" already exists, overwrite the old key value; If the key does not exist, add a key value pair
>>>a={'name':'zhangsan','age':18,'job':'programmer'} >>>a['address']='Xisanqi No. 1 hospital' >>>a['age']=16 >>>a {'name': 'zhangsan', 'age': 16, 'job': 'programmer', 'address': 'Xisanqi No. 1 hospital'}
2. Use update() to add all key value pairs in the new dictionary to the old dictionary object. If the key is duplicate, it will be overwritten directly
>>>a={'name':'zhangsan','age':18,'job':'programmer'} >>>b={'name':'wangwu','money':1000,'sex':'male'} >>>a.update(b) >>>a {'name': 'wangwu', 'age': 18, 'job': 'programmer', 'money': 1000, 'sex': 'male'}
3. del() method can be used to delete elements in the dictionary; Or clear() deletes all key value pairs; pop() deletes the specified key value pair and returns the corresponding "value object";
>>>a={'name':'zhangsan','age':18,'job':'programmer'} >>>del(a['name']) >>>a {'age': 18, 'job': 'programmer'} >>>b=a.pop('age') >>>b 18 >>>a.clear() >>>a {}
4.popitem(): randomly delete and return the key value pair. Dictionary is an "unordered variable sequence", so there is no concept of the first element and the last element; popitem pops up random items because the dictionary has no "last element" or other concepts about order. This method is very effective if you want to remove and process items one by one (because you don't have to get the list of keys first)
>>>a.popitem() ('job', 'programmer') >>>a {'name': 'zhangsan', 'age': 18} >>>a.popitem() ('age', 18) >>>a {'name': 'zhangsan'}
Sequence unpacking
- Sequence unpacking can be used for tuples, lists and dictionaries. Sequence unpacking allows us to easily assign values to multiple variables
>>>x,y,z=(20,30,10) >>>x 20 >>>y >>>30 >z 10 >>>(a,b,c)=(9,8,10) >>>a 9 [a,b,c]=[10,20,30] >>>b 20
When sequence unpacking is used in a dictionary, the "key" is operated by default; If you need to operate on key value pairs, you need to use items(); If you need to operate on values, you need to use values ()
s={'name':'zhangsan','age':18,'job':'teacher'} a,b,c = s #a. B, C receive dictionary keys a 'name' b 'age' c 'job' e,d,f = s.values() #e. D, f receive dictionary values e 'zhangsan' d 18 f 'teacher' h,i,j = s.items() #hij receives the key value pairs of the dictionary h ('name', 'zhangsan') i ('age', 18) j ('job', 'teacher') h[1] 'zhangsan'
Table data is stored and accessed using dictionaries and lists
full name | Age | salary | city |
Xiao Yi Gao | 18 | 30000 | Beijing |
Gao Xiaoer | 19 | 20000 | Shanghai |
Gao Xiaosan | 20 | 10000 | Shenzhen |
>>>r1 = {'name':'Xiao Yi Gao','age':18,'salary':30000,'city':'Beijing'} >>>r2 = {'name':'Gao Xiaoer','age':19,'salary':20000,'city':'Shanghai'} >>>r3 = {'name':'Gao Xiaowu','age':20,'salary':10000,'city':'Shenzhen'} >>>tb=[r1,r2,r3] #Get a second person's salary >>>print(tb[1].get('salary')) #Print all salaries in the table >>>for i in range(len(tb)): #i-->0,1,2 >>> print(tb[i].get('salary')) #Print all data in the table >>>for i in range(len(tb)): >>> print(tb[i].get('name'),tb[i].get('age'),tb[i].get('salary'),tb[i].get('city')) result: 20000 30000 20000 10000 Gao Xiaoyi 18 30000 Beijing Gao Xiaoer 19 20000 Shanghai Gao Xiaowu 20 10000 Shenzhen
Dictionary core underlying principles (important)
The core of the dictionary object is the hash table. A hash table is a sparse array (an array that always has blank elements), and each element of the array
The unit is called a bucket. Each bucket has two parts: one is the reference of the key object and the other is the reference of the value object.
Because: the bucket result is consistent with the size, we can read the specified bucket through the offset.
It is too long to put a key value pair at the bottom of the dictionary
>>>a={} >>> A['name']='gaoqi'
Suppose that after the dictionary a object is created, the array length is 8:
We need to put the key value pair 'name' = 'zhangsan' into the dictionary object a. the first step is to calculate
Hash value for key 'name'. In Python, it can be calculated by hash().
>>>Bin (hash ('name ') #bin conversion binary
'0b1010111101001110101100100101' # try to convert this string of numbers to 0-7
#It can be converted by taking three digits in turn
Binary correspondence: 0 - 000 / 1-001 / 2-010 / 3-011 / 4-100 / 5-101 / 6-110 / 7-111
Since the array length is 8, we can take the rightmost 3 digits of the calculated hash value as the offset, that is, '101', and the decimal number is 5 Let's check whether the bucket corresponding to offset 5 is empty. If it is empty, put the key value pair in. If it is not empty, take the right 3 as the offset in turn, that is, '100', and the decimal system is the number 4 Then check whether the bucket with offset of 4 is empty. Until an empty bucket is found, put the key value pair in. The flow chart is as follows:
The underlying process of finding "key value pair" according to the key (take)
We understand how a key value object is stored in an array. It is simple to get the value object according to the key object
>>>a.get('name') 'gaoqi'
When we call a.get('name '), we find the "key value pair" according to the key' name ', so as to find the value object "gaoqi"
In the first step, we still need to calculate the hash value of the "name" object:
>>>bin(hash('name')) #bin conversion binary '0b1010111101001110110101100100101'
Consistent with the stored underlying process algorithm, it is also a number at different positions of the hash value in turn. Assuming that the array length is 8, we can take the rightmost 3 digits of the calculated hash value as the offset, that is, '101', and the decimal number is 5 Let's check whether the bucket corresponding to offset 5 is empty. If empty, returns None. If it is not empty, calculate the corresponding hash value of the bucket's key object and compare it with our hash value. If it is equal, it will be used. The corresponding value object is returned. If they are not equal, take other digits in turn and recalculate the offset. After taking them in turn, they still can't be found. Then return to None. The flow chart is as follows:
Usage Summary:
- The key must be hashable
- Arrays, strings and tuples are hashable
- Custom objects need to support the following three points:
① Support hash() function (hash)
② Support through__ eq__ () method to detect equality
③ If a==b is true, hash (a) = = hash (b) is also true
- Dictionaries are expensive in memory and typically change space for time
- Key query speed is very fast
- Adding new entries to the dictionary may lead to capacity expansion and change the order of keys in the hash table. Therefore, do not modify the dictionary while traversing the dictionary.
aggregate
The collection is unordered and variable, and the elements cannot be repeated. In fact, the bottom layer of the collection is the dictionary implementation. All elements of the collection are "key objects" in the dictionary, so they cannot be repeated and unique.
Collection creation and deletion
1. Create a collection object with {} and add elements with the add () method
>>>a={3,5,7} >>>a {3,5,7} >>>a.add(9) >>>a {9,3,5,7}
2. Use set() to convert iteratable objects such as lists and tuples into sets. If there are duplicate data in the original data, only one is retained
>>>a={'a','b','c','b'} >>>b=set(a) >>>b {'b', 'a', 'c'}
3.remove() deletes the specified element; clear() clears the entire collection
>>>a={10,20,30,40} >>>a.remove(20) >>>a {40, 10, 30}
Collection related operations
Like concepts in mathematics, Python also provides Union, intersection, difference and other operations for sets. Example:
>>>a={1,3,'sxt'} >>>b={'he','it','sxt'} >>>a|b #Union {1, 'it', 3, 'sxt', 'he'} >>>a&b #intersection {'sxt'} >>>a-b #Difference set (remove the same part of a as b) {1, 3} >>>a.union(b) #Union {1, 'it', 3, 'sxt', 'he'} >>>a.intersection(b) #intersection {'sxt'} >>>a.difference(b) #Difference set {1, 3}
Chapter 4 control statement
Select structure
Single branch structure
The syntax of If statement single branch structure is as follows:
If conditional expression:
Statement / statement block
Of which:
① Conditional expression: logical expression, relational expression, arithmetic expression, etc.
② Statement / statement block: it can be one statement or multiple statements. For multiple statements, the indent must be aligned.
[operation] enter a number. If it is less than 10, the number will be printed
num = input("Please enter a number:") if int(num)<10: print(num)
Please enter a number: 5
5
Detailed explanation of conditional expression
In the selection and loop structure, the value of the conditional expression is False as follows:
False, 0, 0.0, null value None, empty sequence object (empty list, empty tuple, empty collection, empty dictionary, empty string), empty range object, empty iteration object
True in all other cases. In this way, all legal expressions in Python can be regarded as conditional expressions, even including the expression of function calls
[operation] test various conditional expressions
f 3: #Integer as conditional expression print('ok') a=[] #List is used as a conditional expression. Because it is an empty list, it is false if a: print('Empty list is False') s='False' #Non empty string, True if s: print('Non empty string') c=9 if 3<c<20: print('3<c"20') if 3<c and c<20: print("3<c and c< 20") if True:#Boolean value print('True')
The results are as follows:
ok
Non empty string
3<c"20
3<c and c< 20
True
The assignment operator '=' cannot be present in a conditional expression
In python, the assignment operator "=" cannot appear in conditional expressions, which avoids the trouble caused by mistakenly writing the relational operator "= =" as the assignment operator "=" in other languages. The following code will report syntax errors:
If 3<c and (c=20):
Print('assignor cannot appear in conditional expression ')
Double branch selection structure
The syntax format of double branch structure is as follows:
If conditional expression:
Statement 1 / statement block 1
else:
Statement 2 / statement block 2
[operation] enter a number. If it is less than 10, it will print a number less than 10, and if it is greater than 10, it will print a number greater than 10
a =input("Please enter a number:") #The result is a string if int(s)<10: print("s Is a number less than 10") else: print("s Is a number greater than or equal to 10")
Ternary conditional operator
Python provides ternary operators that can be used in some simple double branch assignment situations. The syntax format of ternary conditional operator is as follows:
Value when condition is true if (conditional expression) else value when condition is false
The previous case code can be implemented with ternary conditional operators:
a =input("Please enter a number:") #The result is a string #Test ternary conditional operators print('s Is a number less than 10' if int(s)<10 else 's Is a number greater than or equal to 10')
Multi branch selection structure
The syntax format of multi branch selection structure is as follows:
If conditional expression 1:
Statement block 1 / statement block 1
elif conditional expression 2:
Statement 2 / statement block 2
...
elif conditional expression n:
Statement n / statement block n
[else:
Statement n+1 / statement block n+1
]
[note] in the computer industry, when describing the syntax format, brackets [] are usually used to indicate optional and not required
In the multi branch structure, there is a logical relationship between several branches, which can not be inverted at will
[operation] enter a student's score and convert it into a simple description: Fail (less than 60), pass (60-79), good (80-89), excellent (90-100)
Method 1 (using complete conditional expression)
score = int(input('Please enter a score:')) grade = '' if score<60: grade='fail,' if (60<= score < 80): grade='pass' if (80 <= score < 90): grade='good' if (90 <= score < 100): grade = 'excellent' print('The score is{0},The grade is{1}'.format(score,grade))
Each branch uses independent and complete judgment, and the order can be moved freely without affecting the operation of the program
Method 2 (using multi branch structure)
score = int(input('Please enter a score:')) grade = '' if score<60: grade='fail,' elif score<80: grade='pass' elif score<90: grade='good' elif score < 100: grade = 'excellent' print('The score is{0},The grade is{1}'.format(score,grade))
Select structure nesting
The selection structure can be nested. When using, you must pay attention to controlling the indentation of code blocks at different levels, because the indentation determines the dependency of the code. The syntax format is as follows:
[operation] enter A score. If the score is between 0 and 100, A is above 90, B is above 80, C is above 70, D is above 60 and E is below 60
#Nesting of test selection structures score = int(input('Please enter a score')) if score>100 or score <0: score = int(input('Input error! Please re-enter one in 0-100 Number between')) else: if score>=90: grade = 'A' elif score>=80: grade = 'B' elif score>=70: grade = 'C' elif score>=60: grade = 'D' else: grade= 'E' print('The score is{0},Grade is{1}'.format(score,grade))
#Or you can use the following method with less code.
score = int(input('Please enter a score')) degree = 'ABCDE' num = 0 if score>100 or score <0: print("Please enter a 0-100 Score of") else: num = score/10 if num<6: num = 5 print('The score is{0}, The grade is{1}'.format(score,degree[9 - num]))
Cyclic structure
A loop structure is used to repeatedly execute one or more statements. Express the logic that if the conditions are met, the statements in the loop body are executed repeatedly. After each execution, it will judge whether the sequential condition is True. If it is True, the statements in the loop body will be executed repeatedly. The diagram is as follows:
The statements in the loop body should at least contain statements that change the conditional expression to make the loop tend to end; Otherwise, it will become an endless cycle.
While Loop
The syntax format of While loop is as follows:
While conditional expression:
Loop body statement
[operation] use the while loop to print numbers from 0 to 10
num = 0 while num<=10: print(num,end='\t') num +=1
The results are as follows:
0 1 2 3 4 5 6 7 8 9 10
[operation] use the while loop to calculate the cumulative sum of numbers between 1-100; calculate the cumulative sum of direct even numbers from 1-100 and the cumulative sum of direct odd numbers from 1-100
num=0 Sum_all = 0 #1-100 cumulative sum of all numbers Sum_even=0 #Cumulative sum of 1-100 even numbers Sum_odd = 0 #Cumulative sum of 1-100 odd numbers While num<=100: Sum_all +=num if num%2==0: Sum_even +=num else: Sum_odd +=num num+=1 #Iteration, change the conditional expression to make the loop tend to end