First, the dictionary.
1. Definition: the dictionary is an unordered variable sequence of key value pairs, which is divided into key object and value object. Where, the key object is immutable data (integer, floating-point number, string, tuple), and the key is not repeatable.
Reminder: in the list, we find the corresponding object according to the subscript number. In the dictionary, we find the value through the key
2. Dictionary creation
(1) , {} or dict () create. As follows:
a={'name':'lhy','age':18} >>> a {'name': 'lhy', 'age': 18} >>> b=dict(name='lhy',age=18) >>> b {'name': 'lhy', 'age': 18} >>> c=dict([('name','lhy'),('age',18)]) >>> c {'name': 'lhy', 'age': 18}
Note: in the second method, the key does not need to be enclosed in double quotes.
(2) zip() function establishment
As follows:
d=[1,2,3] >>> e=[4,5,6] >>> f=dict(zip(d,e)) >>> f {1: 4, 2: 5, 3: 6} >>>
Note: the zip method is used to generate tuples. Here, tuples are converted into dictionaries, similar to the third method above
(3) Create a dictionary with null value through fromkeys()
q=dict.fromkeys([1,2,3]) >>> q {1: None, 2: None, 3: None}
3. Dictionary access
(1) Direct access: a [key]
(2)get()
(3) List all key value pairs: a.items()
List all keys: a.keys()
List all values: a.values()
(4) Number of len() key value pairs
(5) Detects whether a key exists. in
The code is as follows:
a {'name': 'lhy', 'age': 18} >>> a['name'] 'lhy' >>> a.get('name') 'lhy' >>> a.get('1') >>> print(a.get('1')) None >>> a.items() dict_items([('name', 'lhy'), ('age', 18)]) >>> a.keys() dict_keys(['name', 'age']) >>> a.values() dict_values(['lhy', 18]) >>> len(a) 2 >>> 'name'in a True >>> '1'in a False >>>
4. Addition, modification and deletion of dictionary elements
(1) Add directly, overwrite old key if key already exists
(2) Use update () to merge two dictionaries into one
(3) del() deletes the specified key value pair
(4) clear() deletes all key value pairs
(5) pop() deletes the specified key value pair and returns the corresponding value object
(6) popitem() randomly deletes key value pairs and returns them (because the dictionary is unordered, it is deleted randomly)
The code is as follows:
> a {'name': 'lhy', 'age': 18} >>> b {'name': 'lll', 'x': '2'} >>> a.update(b) >>> a {'name': 'lll', 'age': 18, 'x': '2'} >>> a['c']='3' >>> a {'name': 'lll', 'age': 18, 'x': '2', 'c': '3'} >>> del(a['c']) >>> a {'name': 'lll', 'age': 18, 'x': '2'} >>> a.pop('x') '2' >>> a.popitem() ('age', 18) >>> a {'name': 'lll'}
5. Sequence unpacking
The code is as follows:
c {'name': 'lhy', 'age': 18} >>> a,b=c >>> a 'name' >>> b 'age' >>> a,b=c.items() >>> a ('name', 'lhy') >>> b ('age', 18) >>> a,b=c.values() >>> a 'lhy' >>> b 18 >>>
6. Core and underlying principles of dictionary
Note: key must be hash able (number, string, tuple)
Custom object needs to support (1) hash() function
(2) Check eq uality by
(3) If a==b is true, then hash (a) = = hash (b) is true
Do not modify the dictionary while traversing the dictionary, because adding new keys to the dictionary may cause expansion and change the order of key value pairs.
2, Set
1. The set is an unordered variable sequence, and the elements cannot be repeated. The bottom layer of the collection is implemented by dictionary, and the elements in the collection are key objects.
2. Create and delete
(1) Create with {}
(2) Add with add()
(3) Use set () to convert other iteratable objects into sets
(4) remove() removes the specified element
(5) clear() clears the entire collection
The code is as follows:
a={1,2,3} >>> a.add(4) >>> a {1, 2, 3, 4} >>> a.remove(4) >>> a {1, 2, 3} >>> a.clear() >>> a set() >>>
3. Set related operations
(1) Union: a|b or a.union (b)
(2) Intersection: A & B or a.intersection (b)
(3) Difference set: a-b or a.difference (b)
3, Select structure
1. Single branch structure: if conditional expression:
Statement / statement block
Note: input () is output as a string. It can be converted to integer by int()
Conditions considered False in conditional expressions: 0, 0.0, none, False, empty sequence object, empty range object, empty iteration object. All other cases are considered True. And there cannot be an assignment =.
2. Two branch structure: if conditional expression:
Statement / statement block
else:
Statement block 2
Ternary conditional operator: return value with true condition if conditional expression else return value with false condition
Notice that they are separated by spaces. No:
3. Multi branch selection structure: if conditional expression:
Statement / statement block
elif:
Statement block 2
etc.
4. The while loop should note that the condition of the condition expression can be changed in the internal statement, otherwise it will form a dead loop.
Four, practice
1. Input the coordinates of the point (x, y), and judge the quadrant of the point.
x=int(input('Please input x: ')) y=int(input('Please input y: ')) if x==0 and y==0 : print('This point is the origin') else : if x==0 or y==0: print('This point is on the axis') elif x>0 and y>0: print('This point is in the first quadrant') elif x>0 and y<0 : print('This point is in the fourth quadrant') elif x<0 and y>0 : print('This point is in the second quadrant') else: print('This point is in the third quadrant')
2. Calculate the sum of numbers 0 to 10
i=0 sum=0 while i<=10 : sum+=i i+=1 print(sum)
3. Enter a score. If the score is less than 60, it is E, 60 to 70 is D, 70 to 80 is C
80 to 90 is B, 90 to 100 is A
score=int(input('Please enter a score of 0 to 100:')) while score<0 or score >100 : score = int(input(',Input error, please re-enter a score of 0 to 100:')) degree=['A','B','C','D','E'] i=0 if (score//10)<6 : i=5 else : i=score//10 print('Result is{0},Grade is{1}'.format(score,degree[9-i]))
The second method is implemented by if selection
score=int(input('Please enter a score of 0 to 100:')) while score<0 or score >100 : score = int(input(',Input error, please re-enter a score of 0 to 100:')) grade='' if score>89 : grade='A' elif score>79 : grade='B' elif score>69: grade='C' elif score>59 : grade='D' else : grade='E' print('Result is{0},Grade is{1}'.format(score,grade))