Level 1: Additions, deletions, and changes to the list: changes to the guest list
mission details
A list is composed of elements arranged in a certain order, and the elements may change as needed. Among them, the addition, deletion, or modification of list elements is the most common operation. The following is a story about treating guests to illustrate the application scenario of list element operations.
Someone invited a few friends to dinner and initially drew up a guest list guests=['Zhang san','Li si','Wang wu','Zhao liu']
. Later, due to some temporary circumstances, the guest list kept changing:
-
Zhao liu
Said to bring his friendsHu qi
along. -
Zhang san
Unable to come due to emergency. -
Wang wu
Said that his younger brotherWang shi
would attend the banquet on his behalf.
The final guest list is as follows:
['Li si','Wang shi','Zhao liu','Hu qi']
This level requires operations such as adding, deleting, and modifying a given list, and outputting the final list after the change.
related information
Python
A series of built-in operations are provided for the list type, including functions such as append()
, insert()
, pop()
, remove()
etc., which can easily handle the above-mentioned list element changes.
We take the guest list above as an example to introduce these list operation methods.
Add list element
Python
append()
Functions such as and are provided insert()
to implement the function of adding new elements to a list.
(1). Adding an element at the end of a list InPython
, you can useappend()
the method to append an element to the end of a list. The basic syntax is as follows:
source_list.append(obj)
in,
source_list
: for the list to be modifiedobj
: for the element to be inserted
For example, to guests
add guests to the end of the list Hu qi
, the corresponding statement would be:
# 初始化guests列表
guests=['Zhang san','Li si','Wang wu','Zhao liu']
# 向guests列表尾部追加一个名为Hu qi的客人
guests.append('Hu qi')
# 输出新的guests列表
print(guests)
The output is:['Zhang san','Li si','Wang wu','Zhao liu','Hu qi']
(2). Add an element at the specified position in the list
Python
It also provides insert()
a method to insert elements at any specified position in the list. The basic syntax is:
source_list.insert(index,obj)
in,
source_list
: for the list to be modifiedindex
: Index of the position to be insertedobj
: for the element to be inserted
注意:在Python中,列表起始元素的位置索引为0
For example, to add guests to the back of guests
the list , the corresponding statement is:Zhang san
Hu qi
# 创建并初始化guests列表
guests=['Zhang san','Li si','Wang wu','Zhao liu']
# 向guests列表Zhang san后面增加一个名为Hu qi的客人
guests.insert(1,'Hu qi')
# 输出新的guests列表
print(guests)
The output is:['Zhang san','Hu qi','Li si','Wang wu','Zhao liu']
modify list elements
Python
The method of modifying list elements in is to directly point out the index of the element to be modified in the list, and then specify a new value for it. Its basic syntax is as follows:
source_list[index] = obj
in,
source_list
: the list to be modifiedindex
: The position index of the element to be modifiedobj
: the new value for the element to be
For example, change the guest list guests
to . , the corresponding statement is:Wang wu
Wang shi
# 初始化guests列表
guests=['Zhang san','Li si','Wang wu','Zhao liu']
# 将列表中的`Wang wu`改为`Wang shi`
guests[2] = 'Wang shi'
# 输出新的guests列表
print(guests)
The output is:['Zhang san','Li si','Wang shi','Zhao liu']
delete list element
Python provides a variety of different methods to delete elements in the list, including the method of deleting elements according to the element index position or element value.
(1). Delete the element at the specified position
del method
In Python, calling del
a function can delete the element at the specified index position, and its basic syntax is as follows:
del source_list[index]
in,
source_list
: the list to be modifiedindex
: The position index of the element to be deleted
For example, remove the guest list guests
from the list Zhang san
. , the corresponding statement is:
# 初始化guests列表
guests=['Zhang san','Li si','Wang wu','Zhao liu']
# 将列表中的`Zhang san`删除
del guests[0]
# 输出新的guests列表
print(guests)
The output is:['Li si','Wang wu','Zhao liu']
The pop method Python
also provides pop()
a method to delete an element, which will delete the corresponding element from the source list and return the deleted element. Its basic syntax is as follows:
deleted_obj = source_list.pop(index)
in,
deleted_obj
: To save the variable of the deleted element, it can be freely named as requiredsource_list
: the list to be modifiedindex
: The position index of the element to be deleted
注意:index参数为可选项,不填则默认删除列表末尾的元素
For example, remove the guest list guests
from the list Zhang san
. , the corresponding statement is:
# 初始化guests列表
guests=['Zhang san','Li si','Wang wu','Zhao liu']
# 将列表中的`Zhang san`删除
deleted_obj = guests.pop(0)
# 输出被删除的元素以及删除后的guests列表
print(deleted_obj)
print(guests)
The output is:Zhang san
['Li si','Wang wu','Zhao liu']
(2). Delete the element corresponding to the specified value Sometimes we don't know the position index of the element to be deleted, what should we do? Don't worry, Python also providesremove()
a method to delete the corresponding element directly through the element value. Its basic syntax is as follows:
source_list.remove(obj)
in,
source_list
for the list to be modifiedobj
is the value of the element to be deleted
注意:如果列表中有多个值为obj的元素,remove仅删除位置索引最靠前的那个元素
For example, remove the guest list guests
from the list Zhang san
. , the corresponding statement is:
# 初始化guests列表,列表中有多个名为Zhang san的客人
guests=['Zhang san','Li si','Wang wu','Zhao liu','Zhang san']
# 将列表中的`Zhang san`删除
guests.remove('Zhang san')
# 输出新的guests列表
print(guests)
The output is:
`['Li si','Wang wu','Zhao liu','Zhang san']`
If you want to know more about list operations, please refer to: 【美】Eric Matthes著《Python编程——从入门到实践》第三章
.
programming requirements
The programming task of this level is to complete src/Step1/guests.py
the code of the file and realize the corresponding functions. Specific requirements are as follows:
-
Step1:
guests
Delete the element at the end of the list, and save the value of the deleted element todeleted_guest
a variable; -
step2: Insert to the place where the index position of the list
deleted_guest
after step1 is deleted ;guests
2
-
guests
step3: Delete the element at index position of the list processed by step21
. -
Print out
deleted_guest
the variables of step1; -
Print out the changed
guests
list of step3.
The code framework of the code files involved in this level src/Step1/guests.py
is as follows:
# coding=utf-8
# 创建并初始化Guests列表
guests = []
while True:
try:
guest = input()
guests.append(guest)
except:
break
# 请在此添加代码,对guests列表进行插入、删除等操作
###### Begin ######
####### End #######
Test instruction
The test file of this level is src/Step1/guests.py
, the test process is as follows:
- The platform automatically compiles and runs
guests.py
, and provides test input through standard input; - The platform takes the program output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/Step1/guests.py
a sample test set for a platform pair:
Test Input: zhang san
li si
wang wu
hu qi
liu ba
Expected Output:liu ba
['zhang san', 'liu ba', 'wang wu', 'hu qi']
Test Input: yu yong
gu chao
zeng qi
Expected Output:zeng qi
['yu yong', 'zeng qi']
Let's start your mission, I wish you success!
If you think the content of this level is helpful to you, please like it below.
A positive person is like the sun where it shines, and a negative person is like the moon.
code:
# coding=utf-8
# 创建并初始化Guests列表
guests = []
while True:
try:
guest = input()
guests.append(guest)
except:
break
# 请在此添加代码,对guests列表进行插入、删除等操作
###### Begin ######
del_guests=guests.pop()
print(del_guests)
guests.insert(2,del_guests)
del guests[1]
print(guests)
####### End #######
Level 2: Sorting: Sort the guests
mission details
In general, the elements in the list we create may be unordered, but sometimes we need to sort the list elements.
For example, for the list of experts who participated in the meeting, we need to sort the name of the experts in descending order of the first letter or from the largest to the smallest. For example, we want to sort the five name elements in the guests list below ['zhang san','li si','wang wu','sun qi','qian ba']
according to the order of the first letter from small to large and from large to small. The sorted outputs are:
['li si','qian ba','sun qi','wang wu','zhang san']
['zhang san','wang wu','sun qi','qian ba','li si']
The requirement of this level is to learn how to use the related operations of list sorting to realize the sorting of list elements.
related information
Python
A built-in method is provided for the list data structure sort()
to realize the sorting function of list elements. Its basic syntax is as follows:
source_list.sort(reverse=True)
in,
source_list
: the list to be sorted;sort
: the syntax key word of the list sorting function;reverse
:sort
An optional parameter of the function. If it is set to a valueTrue
, it will perform reverse sorting from largest to smallest. If it is set toFalse
or this parameter is not filled in, it will perform forward sorting from smallest to largest by default.
For example, given a guest list guests
, we sort it alphabetically as follows:
guests = ['zhang san','li si','wang wu','sun qi','qian ba']
guests.sort()
print(guests)
guests.sort(reverse=True)
print(guests)
Program output:
['li si','qian ba','sun qi','wang wu','zhang san']
['zhang san','wang wu','sun qi','qian ba','li si']
-
Note that
sort
the function acts directly on the list to be sorted and modifies its order -
If you want to know more about list operations, please refer to:
【美】Eric Matthes著《Python编程——从入门到实践》第三章
.
programming requirements
The programming task of this level is to complete src/step2/sortTest.py
the function part in the file, and it is required to source_list
sort the elements in the input list according to the order of the first letter from small to large, and output the sorted list.
The code framework of the code files involved in this level src/step2/sortTest.py
is as follows:
#coding=utf-8
# 创建并初始化`source_list`列表
source_list = []
while True:
try:
list_element = input()
source_list.append(list_element)
except:
break
# 请在此添加代码,对guests列表进行排序等操作并打印输出排序后的列表
#********** Begin *********#
#********** End **********#
Evaluation Description
The test file of this level is src/Step2/sortTest.py
, the test process is as follows:
- The platform automatically compiles and runs
sortTest.py
, and provides test input through standard input; - The platform takes the program output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/Step2/sortTest.py
a sample test set for a platform pair:
Test Input: zhang san
li si
hu ba
Expected Output:['hu ba', 'li si', 'zhang san']
Test Input: wang qing
liu ming
bai zong
Expected Output:['bai zong', 'liu ming', 'wang qing']
Let's start your mission, I wish you success!
It is certainly enviable to have smooth sailing, but the luck bestowed by God is rare and cannot be sought after.
code:
#coding=utf-8
# 创建并初始化`source_list`列表
source_list = []
while True:
try:
list_element = input()
source_list.append(list_element)
except:
break
# 请在此添加代码,对source_list列表进行排序等操作并打印输出排序后的列表
#********** Begin *********#
source_list.sort()
print(source_list)
#********** End **********#
Level 3: List of values: speak with numbers
mission details
In the context of data visualization, lists of numbers Python
are widely used in lists, and lists are very suitable for storing collections of numbers. The goal of this level is to enable readers to master some basic methods of processing number lists, mainly including the creation of number lists, simple statistical operations on number lists, etc.
For example, we want to create a set of even numbers from 2
to 10
, and then calculate the sum of the values of the set.
data_set = [2,4,6,8,10]
sum=30
This level requires the ability to use appropriate methods to quickly create a list of numbers, and to be able to perform simple statistical operations on the values of elements in the list.
related information
In this level, we can use function methods such as range()
, list()
, sum()
and so on to achieve our goal.
range()
function
Python provides range()
functions that can be used to generate a series of continuously increasing numbers. There are three basic usage syntaxes as follows:
range(lower_limit,upper_limit,step)
in,
-
lower_limit
: Generate the lower limit integer of a series of integers, if this parameter is not filled, it defaults to the0
beginning. Generated integers start at and include this number. -
upper_limit
: Generates the upper bound integer of the series of integers, a required parameter. Generate integers that are less than this upper limit. -
step
: The interval step between the series of integers generated between the lower limit and the upper limit, if this parameter is not filled, the default step size is1
-
Note that
range()
the three parameters of the function can only be integers. Ifrange
there is only one parameter in the function, that parameter meansupper_limit
; if there are only two parameters, they meanlower_limit
and respectivelyupper_limit
.
For example, to generate 1~6
a series of integers with a step size of 2 between:
for i in range(1,6,2):
print(i)
Output result:
1
3
5
range()
Create a list of numbers based on a function
We can use range()
functions append()
to create a list using the insertion functionality provided by Python lists.
For example, we want to create a 0~9
list containing the squares of 10 integers:
# 声明一个列表变量
numbers = []
# 利用append()函数和range()函数向列表插入目标元素
for i in range(10):
number = i**2
numbers.append(number)
print(numbers)
Output result:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Create lists of numbers using list()
functions and functionsrange()
We can use list()
the function to range()
convert the generated series of numbers directly into a list. At this time, range()
the return value of the function will be used as list()
the parameter of the function, and the output will be a list of numbers. Its basic usage syntax is as follows:
data_list = list(range(lower_limit,upper_limit,step))
in,
list
: syntax keyword for list functionsrange
:function syntax keyworddata_list
: the final generated list variable
For example, we want to generate and output a list of numbers from 1 to 5:
data_list = list(range(1,6))
print(data_list)
Output result:[1,2,3,4,5]
Perform simple statistical operations on lists of numbers
There are some functions in Python that deal with simple statistical operations on lists of numbers. Using these functions, you can easily find a series of statistical operations such as the minimum, maximum, and sum of the list of numbers. Its basic syntax is as follows:
min_value = min(data_list)
max_value = max(data_list)
sum_value = sum(data_list)
in,
min
: The syntax keyword for finding the minimum value of a list of numbersmax
: syntax keyword for finding the maximum value of a list of numberssum
: syntax keyword for summing a list of numbers
Specific usage examples are as follows:
numbers = [2,4,11,1,21,32,5,8]
print('The min number is',min(numbers))
print('The max number is',max(numbers))
print('The sum is',sum(numbers))
Output result:
The min number is 1
The max number is 32
The sum is 84
If you want to know more about list operations, please refer to:
【美】Eric Matthes著《Python编程——从入门到实践》第三章
.
programming requirements
The programming task is to complete src/Step3/numbers_square.py
the code content of the file to achieve the following functions:
- step1: According to the given lower limit
lower
, upper limitupper
and step sizestep
, use the range function to generate a list - step2: Calculate the length of the list
- step3: Find the difference between the largest element and the smallest element in the list
The code framework of the code file of this level src/Step3/numbers_square.py
is as follows:
#coding=utf-8
# 创建并读入range函数的相应参数
lower = int(input())
upper = int(input())
step = int(input())
# 请在此添加代码,实现编程要求
###### Begin ######
####### End #######
Evaluation Description
The test file of this level is src/Step3/numbers_square.py
, the test process is as follows:
- The platform automatically compiles and runs
numbers_square.py
, and provides test input through standard input; - The platform takes the program output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/Step3/numbers_square.py
a sample test set for a platform pair:
Test Input: 2
8
1
Expected Output:6
5
Test Input: 0
10
3
Expected Output:4
9
Let's start your mission, I wish you success!
The key to life lies in the mind, spirit and mood. It is very important to strive to make one's thoughts clear, to enrich and support one's spirit, and to have a peaceful and cheerful mood every day.
code:
#coding=utf-8
# 创建并读入range函数的相应参数
lower = int(input())
upper = int(input())
step = int(input())
# 请在此添加代码,实现编程要求
###### Begin ######
sourse_list=list(range(lower,upper,step))
lenth=len(sourse_list)
print(lenth)
print(max(sourse_list)-min(sourse_list))
####### End #######
Level 4: List slicing: your menu and mine
mission details
We learned how to deal with single list elements and all list elements in the first three levels, and in this level we will also learn how to deal with parts of list elements - Python
called slices in this level.
For example, when we go to a restaurant to order food, sometimes your menu and mine are exactly the same, and sometimes the names of some dishes are the same. So how to generate your menu based on the menu I have ordered?
This level allows readers to understand and master the basics of list slicing through the partial copy of the dish name list.
related information
Python
Slicing is a common operation to obtain a subsequence by taking some of its elements from a list. The return result type of the slicing operation is consistent with the object being sliced. To create a slice of an existing list, specify the index numbers of the slice's first and last list elements. Its basic syntax is as follows:
list_slice = source_list[start:end:step]
in,
-
source_list
: list of sources to be sliced -
list_slice
: List of subsequences generated after slicing -
start
: slice start index position, if omitted, start from the beginning -
end
: end index position of the slice, if omitted, cut to the end of the list -
step
: slice step size, an optional parameter, indicating thatN
each element takes one, and the default is 1 -
Note: Slices
range()
are the same as functions, and Python will automatically stop at the element before the end index of the specified slice.
For example, the following is the list of dishes I have ordered. Now the menu ordered by my friend contains my first three dish names, and the friend’s menu is output:
my_menu = ['fish','pork','pizza','carrot']
print(my_menu[1:4:2])
print(my_menu[:3])
print(my_menu[2:])
Output result:['pork','carrot']
['fish','pork','pizza']
['pizza','carrot']
Negative indices return the element at the corresponding interval from the end of the list. The index of the element at the end of the list is from -1
the beginning.
For example, a friend's menu contains the last 3 dish names of my menu:
my_menu=['fish','pork','pizza','carrot']
print(my_menu[-3:])
Output result:['pork','pizza','carrot']
If you want to know more about list operations, please refer to: 【美】Eric Matthes著《Python编程——从入门到实践》第四章
.
programming requirements
The programming task of this level is to complete src/Step4/foods.py
the code content of the file to achieve the following functions:
- Use the slicing method to take
3
each1
, form a subsequence and print it out; - Use the slice method to get the last three elements of the my_menu list to form a subsequence and print it out.
The code framework of the code files involved in this level src/Step4/foods.py
is as follows:
# coding=utf-8
# 创建并初始化my_munu列表
my_menu = []
while True:
try:
food = input()
my_menu.append(food)
except:
break
# 请在此添加代码,对my_menu列表进行切片操作
###### Begin ######
####### End #######
Evaluation Description
The test file of this level is src/Step4/foods.py
, the test process is as follows:
- The platform automatically compiles and runs
foods.py
, and provides test input through standard input; - The platform takes the program output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/Step4/foods.py
a sample test set for a platform pair:
Test Input: pizza
chicken
carrot
apple
banana
Expected Output:['pizza','apple']
['carrot','apple','banana']
Test Input: tomato
eggplant
beet
Expected Output:['tomato']
['tomato','eggplant','beet']
Let's start your mission, I wish you success!
In the duel of hope and despair, victory will belong to hope if you hold it with courage and firm hands.
code:
# coding=utf-8
# 创建并初始化my_menu列表
my_menu = []
while True:
try:
food = input()
my_menu.append(food)
except:
break
# 请在此添加代码,对my_menu列表进行切片操作
###### Begin ######
lenth=len(my_menu)
my_menu1=my_menu[:lenth:3]
print(my_menu1)
my_menu2=my_menu[-3:]
print(my_menu2)
####### End #######