当前位置:网站首页>Day7 list and dictionary jobs
Day7 list and dictionary jobs
2022-07-04 10:38:00 【She was your flaw】
Tuples and dictionaries
One 、 Correlation function
- max、min - For maximum 、 minimum value
max( Sequence )
nums = [34, 89, 78, 65, 90, 23]
print(max(nums), min(nums)) # 90 23
- sum - Finding the sum of elements in a number sequence
sum( Sequence )
nums = [34, 89, 78, 65, 90, 23]
print(sum(nums)) # 379
3.sorted - Sort ; Instead of changing the order of elements in the original sequence, a new list is generated
sorted( Sequence ); sorted(reverse=True)
nums = [34, 89, 78, 65, 90, 23]
new_nums = sorted(nums)
print(nums) # [34, 89, 78, 65, 90, 23]
print(new_nums) # [23, 34, 65, 78, 89, 90]
list . sort(); sort(reverse=True)
nums = [34, 89, 78, 65, 90, 23]
result = nums.sort()
print(nums) # [23, 34, 65, 78, 89, 90]
print(result) # None
len - Get the number of elements in the sequence
len( Sequence )
list - List type conversion
list( Sequence ) - All sequences can be converted into lists ; When converting, directly convert the elements in the sequence into the elements of the list
print(list('abc')) # ['a', 'b', 'c']
print(list(range(3))) # [0, 1, 2]
print(list(enumerate(nums)))
Two 、 List derivation
- List derivation - The essence is to create the expression of the list ( concise )
Structure one :
[ expression for Variable in Sequence ]
Structure II :
[ expression for Variable in Sequence if Conditional statements ]
list1 = [10 for x in range(4)]
print(list1) # [10, 10, 10, 10]
list2 = [x for x in range(4)]
print(list2) # [0, 1, 2, 3]
list3 = [x * 2+1 for x in range(4)]
print(list3) # [1, 3, 5, 7]
scores = [89, 67, 34, 56, 20, 90]
list4 = [x % 10 for x in scores]
- Application of derivation
application 1: Let all elements in the sequence be transformed uniformly
[ expression for Variable in Sequence ]
application 2: Transform the elements in the sequence that meet a certain condition ( Make two different transformations according to whether a certain condition is satisfied )
[ expression 1 if Conditional statements else expression 2 for Variable in Sequence ]
application 3: Extract the elements that meet a certain condition in the sequence ( extract 、 Delete )
[ expression for Variable in Sequence if Conditional statements ]
[89, 67, 34, 56, 10, 90] -> [[0, 89], [1, 67], ...]
nums = [89, 67, 34, 56, 10, 90]
new_nums = [[x, nums[x]] for x in range(len(nums))]
print(new_nums)
practice 1: take nums Divide all even numbers in by 2
[89, 67, 34, 56, 10, 90, 35] -> [89, 67, 17, 28, 5, 45, 35]
nums = [89, 67, 34, 56, 10, 90, 35]
new_nums = [x if x % 2 else x // 2 for x in nums] # x//2, x
print(new_nums)
practice 2: Delete all even numbers ( Extract all odd numbers )
[89, 67, 34, 56, 10, 90, 35] -> [89, 67, 35]
nums = [89, 67, 34, 56, 10, 90, 35]
new_nums = [x for x in nums if x % 2]
print(new_nums)
3、 ... and 、 Ternary operator
Binocular operator :+、-、*、… 、> 、= 、and、or
Monocular operator :not
Ternary operator :if-else
1.C/Java The ternary operator of language
Conditional statements ? expression 1: expression 2 - If the conditional statement holds, the whole operation result is an expression 1 Value , Otherwise, the result of the whole operation is an expression 2 Value
2.python The trinary operator of
expression 1 if Conditional statements else expression 2 - If the conditional statement holds, the whole operation result is an expression 1 Value , Otherwise, the result of the whole operation is an expression 2 Value
age = 18
if age >= 18:
a = ' adult '
else:
a = ' A minor '
print(a)
a = ' adult ' if age >= 18 else ' A minor '
print(a)
Four 、 Tuples
- What tuples (tuple)
Tuples are container data types ; take () As a sign of the container , Multiple elements are separated by commas :( Elements 1, Elements 2, Elements 3,…)
Tuples are immutable ( We can only check ); Tuple order - Subscript operation is supported
Elements : Just like the list
1) An empty tuple
t1 = ()
print(type(t1), len(t1)) # <class 'tuple'> 0
2) Tuples with only one element - The only element must be followed by a comma
list1 = [12]
print(list1, type(list1), len(list1)) # [12] <class 'list'> 1
t2 = (12)
print(t2, type(t2)) # 12 <class 'int'>
t3 = (12,)
print(t3, type(t3)) # (12,) <class 'tuple'>
- In general
t4 = (10, 34, 78)
print(t4)
- In the absence of ambiguity , The parentheses of tuples can be omitted ( Directly separating multiple data with commas is also a tuple )
t5 = 10, 34, 78
print(t5, type(t5))
t6 = 10, 34, 78 * 2
print(t6)
2. check - Get elements
- The way of getting elements from lists tuples support
nums = (23, 45, 90, 78, 6, 34)
print(nums[1], nums[-5])
print('---------------------------------')
for x in nums:
print(x)
print('---------------------------------')
for index in range(len(nums)):
print(index, nums[index])
print('---------------------------------')
for index, item in enumerate(nums):
print(index, item)
print('---------------------------------')
print(nums[1:])
print(nums[::-1])
2). Get elements of tuples through variables 1 - Keep the number of variables consistent with the number of elements in the tuple
point = (10, 23, 12)
x, y, z = point
print(x, y, z)
3). Get elements of tuples through variables 2
If the number of variables is less than the number of elements , Then one of the variables must be preceded by *.
When taking it, let it go first Variables get elements according to the positional relationship , Take all the rest The variable of ( In the form of a list )
info = (' Zhang San ', 18, 175, 180, 90, 67, 89)
name, age, *other = info
print(name, age, other) # Zhang San 18 [175, 180, 90, 67, 89]
name, *other = info
print(name, other) # Zhang San [18, 175, 180, 90, 67, 89]
name, age, *other, math = info
print(name, age, math) # Zhang San 18 89
print(other) # [175, 180, 90, 67]
x, *y, z, m = info
print(x, z, m) # ' Zhang San ' 67 89
print(y) # [18, 175, 180, 90]
*x, y, z = info
print(y, z)
print(x)
- Tuples are immutable lists - All immutable related operation tuples in the list support
+、*
in and not in
Comparison operations
Tuples .count()、 Tuples index()
max、min、sum、sorted、len、tuple
num = [34, 89, 78, 65, 90, 23]
print(max(num))
print(min(num))
print(sum(num))
5、 ... and 、 Dictionaries
- Define a way to save a student's information
stu = [' Xiao Ming ', 20, ' male ', 60, 89, 70, 55]
print(stu[0])
stu = {
'name': ' Xiao Ming ',
'age': 20,
'gender': ' male ',
' weight ': 60,
'math': 89,
' Chinese language and literature ': 70,
' English ': 55
}
print(stu['name'])
- What is a dictionary (dict)
‘’’
A dictionary is a container data type ; take {} As a container mark , Multiple key value pairs are separated by commas :{ key 1: value 1, key 2: value 2, key 3: value 3,…}
The dictionary is changeable ( Support the addition, deletion and modification ); The dictionary is out of order ( Subscript operation is not supported )
Element requirements : Dictionary elements are key value pairs
key - The key must be immutable data ( for example : Numbers 、 character string 、 Tuples ); The key is the only ;
value - No requirement
‘’’
- An empty dictionary :{}
d1 = {
}
print(type(d1), len(d1), bool(d1)) # <class 'dict'> 0 False
- Keys are immutable data
d2 = {
1: 10, 'a': 20, (10, 20): 30}
print(d2)
# d3 = {1: 10, 'a': 20, [10, 20]: 30} # Report errors
- The key is the only
d4 = {
'a': 10, 'b': 20, 'c': 30, 'b': 40}
print(d4) # {'a': 10, 'b': 40, 'c': 30}
- The dictionary is out of order
print({
'a': 10, 'b': 20} == {
'b': 20, 'a': 10}) # True
print([10, 20] == [20, 10]) # False
3. Look up the dictionary
1) check - Get the value of the dictionary
a. Get a single value
‘’’
Dictionaries [ key ] - Get the value corresponding to the specified key in the dictionary , If the key does not exist, the program will report an error !
Dictionaries .get( key )/ Dictionaries .get( key , The default value is ) - Get the value corresponding to the specified key in the dictionary , If the key does not exist, return None Or return to the default value
‘’’
dog = {
'name': ' Wangcai ', 'age': 3, 'breed': ' Local dog ', 'gender': ' Bitch ', 'color': ' black '}
print(dog['name'])
print(dog['gender'])
print(dog.get('name'))
print(dog['height']) # KeyError: 'height'
print(dog.get('height')) # None
print(dog.get('height', 0)) # 0
b. Traverse
adopt for When looping through the dictionary , The cyclic variable gets the keys of the dictionary in turn
‘’’
for Variable in Dictionaries :
loop
‘’’
dog = {
'name': ' Wangcai ', 'age': 3, 'breed': ' Local dog ', 'gender': ' Bitch ', 'color': ' black '}
for key in dog:
print(key, dog[key])
- Dictionaries and lists in practical applications
Define a class to save information
class1 = {
'name': 'python2014',
'address': '23 teach ',
'lecturer': {
'name': ' Yu Ting ', 'age': 18, 'QQ': '726550822'},
'leader': {
'name': ' Shu Ling ', 'age': 18, 'QQ': '23425436', 'tel': '110'},
'students': [{
'name': 'stu1', 'school': ' Tsinghua University ', 'tel': '1123', 'linkman': {
'name': ' Zhang San ', 'tel': '923'}},
{
'name': 'stu2', 'school': ' Panzhihua College ', 'tel': '8999', 'linkman': {
'name': ' Li Si ', 'tel': '902'}},
{
'name': 'stu3', 'school': ' Chengdu University of technology ', 'tel': '678', 'linkman': {
'name': ' Xiao Ming ', 'tel': '1123'}},
{
'name': 'stu4', 'school': ' Sichuan University ', 'tel': '9900', 'linkman': {
'name': ' floret ', 'tel': '782'}},
{
'name': 'stu5', 'school': ' Southwest Jiaotong University ', 'tel': '665', 'linkman': {
'name': ' Lao Wang ', 'tel': '009'}}
]
}
print('----------------------------')
# 1) Get the class name
print(class1['name'])
print('----------------------------')
# 2) Get the instructor QQ
print(class1['lecturer']['QQ'])
# 3) Get the names and schools of all students
for x in class1['students']:
print(x['name'], x['school'])
# 4) Get the phone numbers of all students' contacts
for x in class1['students']:
print(x['linkman']['tel'])
print('--------------------------')
print(class1['leader']['QQ'])
for x in class1['students']:
print(x['linkman']['name'])
print('-----------')
print(class1['students'][0]['linkman']['name'])
List and dictionary assignments
1. Create a list , The list is 10 Geshuzong , Ensure the order of elements in the list , Rearrange the list , And sort the list in descending order
for example : Randomly generated [70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
--- After de duplication [70, 88, 91, 107, 234, 177, 282, 197]
---- null [282, 234, 197, 177, 107, 91, 88, 70]
nums = [70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
new_nums = []
for x in nums:
if x not in new_nums:
new_nums.append(x)
a = new_nums
a = sorted(a, reverse=True)
print(a)
2. Use list derivation , Complete the following requirements
a. Generate a storage 1-100 The median is 3 Data list
The result is [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
a = [x for x in range(3, 100, 10)]
print(a)
b. Use the list to push to yes The integers in the list are extracted
for example :[True, 17, "hello", "bye", 98, 34, 21] --- [17, 98, 34, 21]
nums = [True, 17, "hello", "bye", 98, 34, 21]
new_nums = [x for x in nums if type(x) == int]
print(new_nums)
c. Use list derivation Store the length of the string in the specified list
for example ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
nums = ["good", "nice", "see you", "bye"]
new_nums = [len(x) for x in nums]
print(new_nums) # [4, 4, 7, 3]
4. Have a class dictionary as follows :
class1 = {
'name': 'python2104',
'address': '23 teach ',
'lecturer': {
'name': ' Yu Ting ', 'age': 18, 'QQ': '726550822'},
'leader': {
'name': ' Shu Ling ', 'age': 18, 'QQ': '2343844', 'tel': '110'},
'students': [
{
'name': 'stu1', 'school': ' Tsinghua University ', 'tel': '1123', 'age': 18, 'score': 98, 'linkman': {
'name': ' Zhang San ', 'tel': '923'}},
{
'name': 'stu2', 'school': ' Panzhihua College ', 'tel': '8999', 'age': 28, 'score': 76, 'linkman': {
'name': ' Li Si ', 'tel': '902'}},
{
'name': 'stu3', 'school': ' Chengdu University of technology ', 'tel': '678', 'age': 20, 'score': 53, 'linkman': {
'name': ' Xiao Ming ', 'tel': '1123'}},
{
'name': 'stu4', 'school': ' Sichuan University ', 'tel': '9900', 'age': 30, 'score': 87, 'linkman': {
'name': ' floret ', 'tel': '782'}},
{
'name': 'stu5', 'school': ' Southwest Jiaotong University ', 'tel': '665', 'age': 22, 'score': 71, 'linkman': {
'name': ' Lao Wang ', 'tel': '009'}},
{
'name': 'stu6', 'school': ' Chengdu University of technology ', 'tel': '892', 'age': 32, 'score': 80, 'linkman': {
'name': ' Lao Wang 2', 'tel': '0091'}},
{
'name': 'stu7', 'school': ' Sichuan University ', 'tel': '431', 'age': 17, 'score': 65, 'linkman': {
'name': ' Lao Wang 3', 'tel': '0092'}},
{
'name': 'stu8', 'school': ' Panzhihua College ', 'tel': '2333', 'age': 16, 'score': 32, 'linkman': {
'name': ' Lao Wang 4', 'tel': '0093'}},
{
'name': 'stu9', 'school': ' Panzhihua College ', 'tel': '565', 'age': 21, 'score': 71, 'linkman': {
'name': ' Lao Wang 5', 'tel': '0094'}}
]
}
1 Get class location
print(class1['name']) # python2104
2) Get the name and phone number of the head teacher
print(class1['leader']['name'], class1['leader']['tel'])
3) Get the names and scores of all students
for x in class1['students']:
print(x['name'], x['score'])
4) Get the names and phone numbers of all student contacts
for x in class1['students']:
for y in x['linkman']['name']:
print(y, end=(' '))
for z in x['linkman']['tel']:
print(z, end=(' '))
5) Get the highest score in the class
all_student = class1['students']
max_score = all_student[0]['score']
for stu in all_student[1:]:
s = stu['score']
if s >max_score:
max_score = s
print(' The highest :', max_score)
6) Get the name of the student with the highest score in the class
all_student = class1['students']
max_score = all_student[0]['score']
for stu in all_student[1:]:
s = stu['score']
if s >max_score:
max_score = s
print(' The highest score winner :', end='')
for stu in all_student:
if stu['score'] == max_score:
print(stu['name'], end='')
7) Calculate the average score of students in the class
all_student = class1['students']
sum1 = 0
for stu in all_student:
sum1 += stu['score']
print(' average :', sum1/len(all_student))
8) Count the number of minors in the class
all_student = class1['students']
count = 0
for stu in all_student:
if stu ['age'] < 18:
count += 1
print(' Number of minors :', count)
9) Count the number of people in each school with a dictionary , similar : {' Tsinghua University ': 1, ' Panzhihua College ': 3}
all_student = class1['students']
school_info = {
}
for stu in all_student:
school = stu['school']
school_info[school] = school_info.get(school, 0) + 1
print(school_info)
边栏推荐
- MPLS: multi protocol label switching
- RHCE day 3
- OSPF comprehensive experiment
- leetcode1-3
- Collection of practical string functions
- What is devsecops? Definitions, processes, frameworks and best practices for 2022
- Error C4996 ‘WSAAsyncSelect‘: Use WSAEventSelect() instead or define _ WINSOCK_ DEPRECATED_ NO_ WARN
- Recursion and divide and conquer strategy
- Four characteristics and isolation levels of database transactions
- [Galaxy Kirin V10] [desktop and server] FRP intranet penetration
猜你喜欢
The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
【Day2】 convolutional-neural-networks
The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer
The future education examination system cannot answer questions, and there is no response after clicking on the options, and the answers will not be recorded
If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
Reasons and solutions for the 8-hour difference in mongodb data date display
[Galaxy Kirin V10] [server] KVM create Bridge
TS type gymnastics: illustrating a complex advanced type
Huge number (C language)
Article publishing experiment
随机推荐
Sword finger offer 31 Stack push in and pop-up sequence
Velodyne configuration command
From programmers to large-scale distributed architects, where are you (2)
Jianzhi offer 04 (implemented in C language)
Learning XML DOM -- a typical model for parsing XML documents
[Galaxy Kirin V10] [desktop and server] FRP intranet penetration
Latex arranges single column table pictures in double column format articles
Press the button wizard to learn how to fight monsters - identify the map, run the map, enter the gang and identify NPC
system design
Hidden C2 tunnel -- use of icmpsh of ICMP
Online troubleshooting
MPLS: multi protocol label switching
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction
Reprint: summation formula of proportional series and its derivation process
[Galaxy Kirin V10] [desktop] login system flash back
Basic data types of MySQL
Map container
The future education examination system cannot answer questions, and there is no response after clicking on the options, and the answers will not be recorded
[Galaxy Kirin V10] [server] NFS setup
Time complexity and space complexity