educoder: Getting Started with Python Lists

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 liuSaid to bring his friends Hu qialong.

  • Zhang sanUnable to come due to emergency.

  • Wang wuSaid that his younger brother Wang shiwould 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

PythonA 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

Pythonappend()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 modified
  • obj: for the element to be inserted

For example, to guestsadd guests to the end of the list Hu qi, the corresponding statement would be:

  1. # 初始化guests列表
  2. guests=['Zhang san','Li si','Wang wu','Zhao liu']
  3. # 向guests列表尾部追加一个名为Hu qi的客人
  4. guests.append('Hu qi')
  5. # 输出新的guests列表
  6. 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

PythonIt 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 modified
  • index: Index of the position to be inserted
  • obj: for the element to be inserted

注意:在Python中,列表起始元素的位置索引为0

For example, to add guests to the back of gueststhe list , the corresponding statement is:Zhang sanHu qi

  1. # 创建并初始化guests列表
  2. guests=['Zhang san','Li si','Wang wu','Zhao liu']
  3. # 向guests列表Zhang san后面增加一个名为Hu qi的客人
  4. guests.insert(1,'Hu qi')
  5. # 输出新的guests列表
  6. print(guests)

The output is:['Zhang san','Hu qi','Li si','Wang wu','Zhao liu']

modify list elements

PythonThe 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 modified
  • index: The position index of the element to be modified
  • obj: the new value for the element to be

For example, change the guest list gueststo . , the corresponding statement is:Wang wuWang shi

  1. # 初始化guests列表
  2. guests=['Zhang san','Li si','Wang wu','Zhao liu']
  3. # 将列表中的`Wang wu`改为`Wang shi`
  4. guests[2] = 'Wang shi'
  5. # 输出新的guests列表
  6. 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 dela 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 modified
  • index: The position index of the element to be deleted

For example, remove the guest list guestsfrom the list Zhang san. , the corresponding statement is:

 
 
  1. # 初始化guests列表
  2. guests=['Zhang san','Li si','Wang wu','Zhao liu']
  3. # 将列表中的`Zhang san`删除
  4. del guests[0]
  5. # 输出新的guests列表
  6. 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 required
  • source_list: the list to be modified
  • index: The position index of the element to be deleted

注意:index参数为可选项,不填则默认删除列表末尾的元素

For example, remove the guest list guestsfrom the list Zhang san. , the corresponding statement is:

  1. # 初始化guests列表
  2. guests=['Zhang san','Li si','Wang wu','Zhao liu']
  3. # 将列表中的`Zhang san`删除
  4. deleted_obj = guests.pop(0)
  5. # 输出被删除的元素以及删除后的guests列表
  6. print(deleted_obj)
  7. 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_listfor the list to be modified
  • objis the value of the element to be deleted

注意:如果列表中有多个值为obj的元素,remove仅删除位置索引最靠前的那个元素

For example, remove the guest list guestsfrom the list Zhang san. , the corresponding statement is:

  1. # 初始化guests列表,列表中有多个名为Zhang san的客人
  2. guests=['Zhang san','Li si','Wang wu','Zhao liu','Zhang san']
  3. # 将列表中的`Zhang san`删除
  4. guests.remove('Zhang san')
  5. # 输出新的guests列表
  6. print(guests)

The output is:

  1. `['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.pythe code of the file and realize the corresponding functions. Specific requirements are as follows:

  • Step1: guestsDelete the element at the end of the list, and save the value of the deleted element to deleted_guesta variable;

  • step2: Insert to the place where the index position of the list deleted_guestafter step1 is deleted ;guests2

  • guestsstep3: Delete the element at index position of the list processed by step2 1.

  • Print out deleted_guestthe variables of step1;

  • Print out the changed guestslist of step3.

The code framework of the code files involved in this level src/Step1/guests.pyis as follows:

  1. # coding=utf-8
  2. # 创建并初始化Guests列表
  3. guests = []
  4. while True:
  5. try:
  6. guest = input()
  7. guests.append(guest)
  8. except:
  9. break
  10. # 请在此添加代码,对guests列表进行插入、删除等操作
  11. ###### Begin ######
  12. ####### End #######

Test instruction

The test file of this level is src/Step1/guests.py, the test process is as follows:

  1. The platform automatically compiles and runs guests.py, and provides test input through standard input;
  2. 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.pya sample test set for a platform pair:

Test Input: zhang san li si wang wu hu qi liu baExpected Output:liu ba ['zhang san', 'liu ba', 'wang wu', 'hu qi']

Test Input: yu yong gu chao zeng qiExpected 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

PythonA 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:

  1. source_list.sort(reverse=True)

in,

  • source_list: the list to be sorted;
  • sort: the syntax key word of the list sorting function;
  • reverse: sortAn optional parameter of the function. If it is set to a value True, it will perform reverse sorting from largest to smallest. If it is set to Falseor 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:

  1. guests = ['zhang san','li si','wang wu','sun qi','qian ba']
  2. guests.sort()
  3. print(guests)
  4. guests.sort(reverse=True)
  5. 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 sortthe 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_listsort 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:

  1. #coding=utf-8
  2. # 创建并初始化`source_list`列表
  3. source_list = []
  4. while True:
  5. try:
  6. list_element = input()
  7. source_list.append(list_element)
  8. except:
  9. break
  10. # 请在此添加代码,对guests列表进行排序等操作并打印输出排序后的列表
  11. #********** Begin *********#
  12. #********** End **********#

Evaluation Description

The test file of this level is src/Step2/sortTest.py, the test process is as follows:

  1. The platform automatically compiles and runs sortTest.py, and provides test input through standard input;
  2. 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.pya sample test set for a platform pair:

Test Input: zhang san li si hu baExpected Output:['hu ba', 'li si', 'zhang san']

Test Input: wang qing liu ming bai zongExpected 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 Pythonare 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 2to 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:

  1. 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 the 0beginning. 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. If rangethere is only one parameter in the function, that parameter means upper_limit; if there are only two parameters, they mean lower_limitand respectively upper_limit.

For example, to generate 1~6a series of integers with a step size of 2 between:

  1. for i in range(1,6,2):
  2. print(i)

Output result:

  1. 1
  2. 3
  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~9list containing the squares of 10 integers:

  1. # 声明一个列表变量
  2. numbers = []
  3. # 利用append()函数和range()函数向列表插入目标元素
  4. for i in range(10):
  5. number = i**2
  6. numbers.append(number)
  7. 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:

  1. data_list = list(range(lower_limit,upper_limit,step))

in,

  • list: syntax keyword for list functions
  • range:function syntax keyword
  • data_list: the final generated list variable

For example, we want to generate and output a list of numbers from 1 to 5:

  1. data_list = list(range(1,6))
  2. 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:

  1. min_value = min(data_list)
  2. max_value = max(data_list)
  3. sum_value = sum(data_list)

in,

  • min: The syntax keyword for finding the minimum value of a list of numbers
  • max: syntax keyword for finding the maximum value of a list of numbers
  • sum: syntax keyword for summing a list of numbers

Specific usage examples are as follows:

  1. numbers = [2,4,11,1,21,32,5,8]
  2. print('The min number is',min(numbers))
  3. print('The max number is',max(numbers))
  4. print('The sum is',sum(numbers))

Output result:

  1. The min number is 1
  2. The max number is 32
  3. 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.pythe code content of the file to achieve the following functions:

  • step1: According to the given lower limit lower, upper limit upperand step size step, 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.pyis as follows:

  1. #coding=utf-8
  2. # 创建并读入range函数的相应参数
  3. lower = int(input())
  4. upper = int(input())
  5. step = int(input())
  6. # 请在此添加代码,实现编程要求
  7. ###### Begin ######
  8. ####### End #######

Evaluation Description

The test file of this level is src/Step3/numbers_square.py, the test process is as follows:

  1. The platform automatically compiles and runs numbers_square.py, and provides test input through standard input;
  2. 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.pya sample test set for a platform pair:

Test Input: 2 8 1Expected Output:6 5

Test Input: 0 10 3Expected 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 - Pythoncalled 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

PythonSlicing 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:

  1. 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 that Neach 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:

  1. my_menu = ['fish','pork','pizza','carrot']
  2. print(my_menu[1:4:2])
  3. print(my_menu[:3])
  4. 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 -1the beginning.

For example, a friend's menu contains the last 3 dish names of my menu:

  1. my_menu=['fish','pork','pizza','carrot']
  2. 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.pythe code content of the file to achieve the following functions:

  • Use the slicing method to take 3each 1, 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.pyis as follows:

  1. # coding=utf-8
  2. # 创建并初始化my_munu列表
  3. my_menu = []
  4. while True:
  5. try:
  6. food = input()
  7. my_menu.append(food)
  8. except:
  9. break
  10. # 请在此添加代码,对my_menu列表进行切片操作
  11. ###### Begin ######
  12. ####### End #######

Evaluation Description

The test file of this level is src/Step4/foods.py, the test process is as follows:

  1. The platform automatically compiles and runs foods.py, and provides test input through standard input;
  2. 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.pya sample test set for a platform pair:

Test Input: pizza chicken carrot apple bananaExpected Output:['pizza','apple'] ['carrot','apple','banana']

Test Input: tomato eggplant beetExpected 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 #######

Guess you like

Origin blog.csdn.net/weixin_62174595/article/details/127259833