Summary of Qianfeng education python2104
Seventh summary: dictionaries and collections
catalogue
- Addition, deletion and modification of dictionary
- Dictionary related operations
- aggregate
- character string
- task
text
1. Addition, deletion and modification of dictionary
"""
1. Additions and modifications
DICTIONARY [key] = value - when the key exists, it is the value of the modification key, and when the key does not exist, it is the value of the addition key pair
2. Dictionary SetDefault (key, value) - adds a key pair
"""
cat={'name':'to one's heart's content','age':2} cat['color']='white' #add to cat['color']='yellow' #change print(cat) cat.setdefault('weight',8) #add to print(cat) cat.setdefault('weight',7) #When there are key pairs in the dictionary, they remain unchanged (very useful) print(cat)
#Exercise: add the key value pair corresponding to the score to the students who have no score in the students, and the score value is zero
students = [ {'name': 'stu1', 'tel': '1234', 'score': 89}, {'name': 'stu2', 'tel': '465', 'score': 80}, {'name': 'stu3', 'tel': '678'}, {'name': 'stu3', 'score': 78}, {'name': 'stu4', 'tel': '234'} ] for x in students: x.setdefault('score',0) print(students)
"""
3. Delete delete key pair
del DICTIONARY [key] - delete the key value pair corresponding to the key in the dictionary (an error will be reported if the key does not exist)
Dictionaries. Pop (key) - take out the value corresponding to the specified key in the dictionary (an error will be reported if the key does not exist)
"""
print(cat) del cat['color'] print(cat) age=cat.pop('age') print(cat,age)
2. Dictionary related operations
1. Related operations
The dictionary does not support +, *, nor does it support size comparison operators. Only = ==
Dictionary support in,not in
Key in dictionary
Key not in dictionary
d1={'a':10,'b':20,'c':30} print(10 in d1) #Falsee print('a' in d1) #True
2. Correlation function
len - get the number of keys
Dict (data)
1) The data itself is a sequence
2) Elements in a sequence must have a small sequence of only two elements
3) The first element of a small sequence must be immutable data
data=[('a',10),('b',20)] print(dict(data)) #{'a': 10, 'b': 20} data1=['ab',range(2),[10,20]] print(dict(data1)) #{'a': 'b', 0: 1, 10: 20}
"""
Dictionary to list / tuple - take out the keys to form a list
"""
dic1={'a': 'b', 0: 1, 10: 20} print(list(dic1))
3. Dictionary related methods
Dictionaries. clear() - clear the dictionary
Dictionaries. Copy - copy the original dictionary to produce a new dictionary
Dictionaries. Update - adds all elements in the sequence to the dictionary (overwrites if there is one) The sequence must be a dictionary or a sequence that can be converted to a dictionary
Dictionaries. keys() - get all the keys in the dictionary and return a sequence
Dictionaries. value() - get all the values in the dictionary and return a sequence
Dictionaries. items() - get the key value pairs in the dictionary and return a sequence
dic2={'z':15} list1=['oi','ac'] dic1.update(dic2) dic1.update(list1) print(dic1)
4. Dictionary derivation
{key expression: value expression for variable in sequence}
{expression of key: expression of value for variable in sequence if conditional statement}
#Exercise: exchange keys and values of a dictionary through dictionary derivation
zd={'a':10,'b':20} zd2={zd[x]:x for x in zd} print(zd2) #{10: 'a', 20: 'b'}
3. Ternary operator
1. What is a set
A collection is a container: take {} as the container flag, and multiple elements are separated by commas: {element 1, element 2,...}
The set is variable; The collection is out of order
Element: immutable data, element is unique (with automatic de duplication function)
#1) Empty set
set1=set() print(type(set1),len(set1)) #<class 'set'> 0
#2) The collection is out of order
print({1,2,3}=={3,2,1}) #True
#3) The element must be immutable data
set2={1,'abc',(2,3)} print(set2) #{(2, 3), 1, 'abc'} # set3={1,'abc',[2,3]} # print(set3) #report errors
#4) Element unique
set4={1,2,3,3,3,3} print(set4) #{1, 2, 3}
2. Addition, deletion, modification and query of set elements
#1) Search traversal
for variable in set:
Circulatory body
#2) Increase
Assemble Add (element) - adds the specified element to the collection
Assemble Update - add all elements in the sequence to the collection
#3) Delete
Assemble Remove (element) - delete the specified element, and an error will be reported if the shareholding element does not exist
Assemble Discard (element) - deletes the specified element. If the element does not exist, no error will be reported
#4) Change - the collection cannot directly modify the value of an element. You can only delete it and add it again
num1={1,2,3,4,5} #ergodic for x in num1: print(x) #increase num1.add(6) print(num1) num1.update('abc') print(num1) #Delete num1.remove('a') print(num1) num1.discard('b') print(num1)
3. Mathematical set operation:
&(intersection), | (Union), - (difference set), ^ (symmetric difference set), > / < (true subset), > = / < = (subset)
numa={1,2,3,4,5,6,7} numb={5,6,7,8,9} #intersection print(numa&numb) #Union print(numa|numb) #Difference set print(numa-numb) #Symmetric difference set print(numa^numb) #Subset (possibly equal) / true subset (really smaller than it) print({10,20,30}>{1,2}) #False print({10,20,30}>={10,20,30}) #True
4. String
1. Add, delete and modify query - immutable: add, delete and modify are not supported; Ordered: subscripts are supported
#1) Check str1='hello' #a. Traversal for x in str1: print(x) ''' h e l l o ''' for x,y in enumerate(str1): print(x,y) ''' 0 h 1 e 2 l 3 l 4 o '''
#b. Slice
print(str1[1:3]) #el print(str1[-1:-3:-1]) #ol
#c. Get single
print(str1[2]) #l
2. String operator
#1)+,*
s='Hello' print(s*3) #Hello hello hello d='world' print(s+d) #Hello world
#2)<,>,<=,>=
#The size of the encoded value of the string is compared
a='a' b='b' print(a>b) #False
#3)in,not in
a='a' d='d' abc='abc' print(a in abc) #True print(d not in abc) #True
3.len,str
str2='abcd' print(len(str2)) #4 list1=[1,2,3,6] print(type(str(list1))) #<class 'str'>
5. Operation
- Define a list and save the information of 6 students in the list (student information includes: name, age, grade (single subject), telephone, gender (male, female, unknown))
stu=[ {'name': 'stu1', 'age':18,'gender': 'male', 'tel': '1123', 'score': 56}, {'name': 'stu2','age':17, 'gender': 'male', 'tel': '8999', 'score': 75}, {'name': 'stu3', 'age':19,'gender': 'female', 'tel': '678', 'score': 36}, {'name': 'stu4', 'age':18,'gender': 'female', 'tel': '9900', 'score': 80}, {'name': 'stu5', 'age':20,'gender': 'male', 'tel': '665', 'score': 99}, {'name': 'stu6', 'age':19,'gender': 'Unknown', 'tel': '665', 'score': 61} ]
- Count the number of failed students
num_of_failing_students=0 for score in stu: if score['score']<60: num_of_failing_students+=1 print(num_of_failing_students)
- Print the names of the failed students and the corresponding grades
for students in stu: if students['score']<60: print(students['name'],students['score'],'fail,')
- Print the name of the student whose mobile phone tail number is 8
for students in stu: tel=students['tel'] if int(tel[-1])==8: print(students['name'])
- Print the highest score and the corresponding student's name
top_score=0 for students in stu: score=students['score'] if score>top_score: top_score=score top_score_name=students['name'] print('The highest score is', top_score_name,'of',top_score,'branch')
- Delete all students of Unknown Gender
for index,students in enumerate(stu): if students['gender']=='Unknown': del stu[index] print(stu)
- Sort the list according to the students' grades (struggle, give up if you can't)
#Learn from the powerful version of your classmates
for x in range(len(stu)): i = 0 j = 1 while j<len(stu): if stu[i]['score'] < stu[j]['score']: k = stu[j] stu[j] = stu[i] stu[i] = k i+=1 j+=1 print(stu)
#Write your own stupid way
score_list=[] stu1=[] for index,students in enumerate(stu): score=students['score'] score_list.append(score) score_list.sort(reverse=True) for x in score_list: for index, students in enumerate(stu): if students['score']==x: stu1.append(students) print(stu1)
- Use three sets to represent the names of students who choose courses in three disciplines (a student can choose multiple courses at the same time)
math={'AI aa','Zhizi','Luo Ji'} Chinese={'Cheng Xin','First Emperor of Qin','Zhizi','AI aa','Mozi'} universe_sociology={'Luo Ji','Guan Yifan','Zhizi','Yun Tianming'}
-
How many students are there in total
print(len(math|Chinese|universe_sociology)) -
Find the number of people who only selected the first subject and their corresponding names
print(len(math),math) -
Find the number of students who have chosen only one subject and their corresponding names
a=math|Chinese|universe_sociology b=math&Chinese c=math&universe_sociology d=universe_sociology&Chinese print(len(a-b-c-d),a-b-c-d)
- Find the number of students who have chosen only two subjects and their corresponding names
a=math&Chinese&universe_sociology b=math&Chinese c=math&universe_sociology d=universe_sociology&Chinese print(len((b|c|d)-a),(b|c|d)-a)
- Find the number of students who have selected three courses and their corresponding names
a=math&Chinese&universe_sociology print(len(a),a)