Welcome to stationmaster School, learning Webmaster Online Zero basics, an online course Python Complete self-study course is for you today share It's lesson 14< Python Medium list >. This class is a big one. I'll explain these knowledge points in detail: Creating and deleting lists,Access list elements,Traversal list,Add list element,Modify list elements,Delete list element,Count and calculate the list,Sort the list,List derivation,Application for creating and accessing two-dimensional lists.
There is a list of songs, website Inside classification There are in the table of contents page article List, so the list is no stranger to you.
stay Python In, a list is a series of elements arranged in a specific order. It is a built-in variable sequence in Python.
Formally, all elements of the list are placed in a pair of brackets "[]", and two adjacent elements are separated by English commas ",".
On the content, the list can integer,real number,character string , list tuple,Dictionaries,aggregate Any type of element is put into the list, and the type of element can be different in the same list.
The following lesson arranges and explains the knowledge points related to the list:
15.1,Creating and deleting lists in Python
In Python Create list There are mainly the following methods:
15.1.1. Create a list using the assignment operator "=" in Python:
In Python, to create a list, you can use the assignment operator "=" to create a list, with assignment on the right and assignment on the left variable . the specific syntax is as follows:
listname = [element 1 , element 2 , element 3 , ... , element n]
Where, listname represents the name of the list, which can be any name that conforms to Python naming rules identifier ; element 1 and element 2 represent the elements in the list. There is no limit to the number of these elements. In terms of content, as long as they are the data types supported in Python, such as integer, real number, string, list and tuple.
The following are all legal lists:
shuzi = [1,2,3,4,5,6,7] #number shige = ["abed, I see a silver light","It's suspected to be frost on the ground","look at the bright moon","Bow your head and think of your hometown"] #Poetry hunhe = [66,"Python",'Life is short, I use it Python',["WEB development","cloud computing","Reptile"]] #Mixed string python = ['grace',"to make clear",'''simple''']
In actual use, we usually just put the same type of data in a list. For example, Shizi, Shige and python above all have the same data type, while hunhe's string is mixed and has poor readability. It's estimated that we don't even know what it means.
15.1.2. Create an empty list in Python []
In Python, you can create an empty list, such as creating an empty list code as follows
kong = []
15.1.3. Use the list() function in Python to create a numeric list
In Python, you can use the list() function to directly range The result of () function loop is converted into a list.
Let's first review the use of the range() function:< Loop statements in Python >(learned inside)
range(start,end,step)
The parameters are described as follows:
start: used to specify the starting value of the technology. It can be omitted. If omitted, it starts from 0.
End: used to specify the end value of the count and cannot be omitted. The end value does not include this value. For example, range (100), it means the value is 0 ~ 99. When the range() function has only one parameter, it means the end value of the specified count.
Step: used to specify the step size, that is, the interval between two numbers. If omitted, it means that the step size is 1. For example, range (1,7) means that the values are 1, 2, 3, 4, 5 and 6
The usage of the list() function is as follows:
list(data)
Where, data represents data that can be converted into a list, including range objects, strings, tuples, or other data that can be iterated.
For example, to create a list of all even numbers from 0 to 20 (excluding 20), you can use the following code:
list(range(0,20,2))
The operation results are as follows:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>>
Note: using the list() function, you can create a list not only through the range object, but also through other function objects. Other functions will be learned later.
15.1.4 delete list in Python
In Python, it is easy to delete a list that has been created del The syntax format is as follows:
del List name
For example, delete a list called shige:
shige = ["abed, I see a silver light","It's suspected to be frost on the ground","look at the bright moon","Bow your head and think of your hometown"] del shige
However, if you delete a nonexistent list, an error will be reported, such as:
shige = ["abed, I see a silver light","It's suspected to be frost on the ground","look at the bright moon","Bow your head and think of your hometown"] del sg
Of course, the above lists are the same whether shige is defined or not. The deleted sg list does not exist. The error results are as follows:
Traceback (most recent call last): File "D:\Python\Python310\Doc\000.py", line 1, in <module> del sg NameError: name 'sg' is not defined >>>
In actual development, del is not often used to delete lists, because Python's built-in garbage collection mechanism will automatically destroy useless lists. Python will automatically recycle them even if developers do not delete them manually.
15.2,Accessing list elements in Python
In Python, if it is relatively simple to output the contents of the list, use print () function.
For example, we can output the mixed hunhe list in the content of the last knowledge point by using the function print(hunhe)
shuzi = [1,2,3,4,5,6,7] #number shige = ["abed, I see a silver light","It's suspected to be frost on the ground","look at the bright moon","Bow your head and think of your hometown"] #Poetry hunhe = [66,"Python",'Life is short, I use it Python',["WEB development","cloud computing","Reptile"]] #Mixed string python = ['grace',"to make clear",'''simple'''] print(hunhe)
The results are as follows:
[66, 'Python', 'Life is short, I use it Python', ['WEB development', 'cloud computing', 'Reptile']] >>>
Output python as follows:
['grace', 'to make clear', 'simple'] >>>
After comparison, single quotation marks, double quotation marks and three quotation marks are not input, but single quotation marks are output.
Through the above output, we find that when outputting the list, the brackets [] on both sides are included.
A list is an ordered collection, so Access list For any element in, you only need to tell Python the location (index) of the element Access list elements , first indicate the name of the list, and then indicate the position of the element in the list.
Next, let's output the third element in the mixed list, code As follows:
hunhe = [66,"Python",'Life is short, I use it Python',["WEB development","cloud computing","Reptile"]] print(hunhe[2])
The output results are:
Life is short, I use it Python >>>
As can be seen from the above results, brackets [] are not included in the output of a single list. If it is a string, the left and right quotation marks are not included.
Example: let's output the daily language.
import datetime #Import date time class mot = ["Trust is the most scarce currency.", #Define a list "Pursue fast, but die miserably; sometimes, slow is fast!", "Adaptation is a technology. If you learn adaptation technology, you will change words into gold. You won't be short of money in your life.", "Flow is natural, customers are natural, and methods are natural.", "Every time you spend is precious. You should focus on the most productive things.", "Everything is not for me, everything is for my use.", "The diamond is in your backyard, the secret collection is in front of you, but you turn a blind eye to it every day."] day=datetime.datetime.now().weekday() #Get current week print(mot[day]) #Output daily language
Note: in the above code, datetime.datetime.now() is used to obtain the current date, and weekday() is used to obtain the week from the date time object. Its value is one of 0 ~ 6, 0-bit Monday, and 6 is Sunday.
The operation results on October 31, 2021 are as follows:
The diamond is in your backyard, the secret collection is in front of you, but you turn a blind eye to it every day. >>>
This knowledge point is through index( index )To access list elements, you can access list elements by slicing.
15.3,Traversing lists in Python
Let's first explain the meaning of traversal. It means all-round and everywhere, and calendar means line and travel. The so-called traversal means to travel all over and around.
Traversal list Is to get data from the list from beginning to end.
Traversing all elements in the list is a common operation. In the process of traversal, you can complete functions such as query and processing.
In Python, there are many ways to traverse lists. Here are some common traversal methods:
15.3.1 direct use for Loop through the list
Directly use the for loop to traverse the list, and only the value of the element can be output. The syntax format is as follows:
for variable element in list: #output variable element
For example, define the design concept of python, then traverse the list through the for loop and output each content. code As follows:
print("Python Design concept") python = ["grace","to make clear","simple"] for linian in python: print(linian)
The results after implementation are as follows:
Python Design concept grace to make clear simple >>>
15.3.2. Use for loop and enumerate () function traversal list
Using the for loop and enumerate() function, you can output the index value and element content at the same time. Its syntax format is as follows:
for index,Variable element in enumerate(list) #Output index and variable elements
For example, define the design concept of python, then traverse the list through the for loop and enumerate() function, and output the index and each content. The code is as follows:
print("Python Design concept") python = ["grace","to make clear","simple"] for index,linian in enumerate(python): print(index,linian)
The results are as follows:
Python Design concept 0 grace 1 to make clear 2 simple >>>
15.3.3. Use the for loop and list() function to traverse the list
For example, define the design concept of python, then traverse the list through the for loop and the list() function and output each content. The code is as follows:
print("Python Design concept") python = ["grace","to make clear","simple"] for linian in list(python): print(linian)
The results are as follows:
Python Design concept grace to make clear simple >>>
15.3.4. Use the for loop and range() function to traverse the list
Define the list of number, then traverse the list through the for loop and the range() function and output each content. The code is as follows:
number = [1122,2366,4400,5577,8888] for i in range(len(number)): print(i,number[i])
The execution results are:
0 1122 1 2366 2 4400 3 5577 4 8888 >>>
You can output without index. The code is:
number = [1122,2366,4400,5577,8888] for i in range(len(number)): print(number[i])
The operation result is:
1122 2366 4400 5577 8888 >>>
We put the output results on the same line, and the code is:
number = [1122,2366,4400,5577,8888] for i in range(len(number)): print(number[i],end=" ")
The execution results are:
1122 2366 4400 5577 8888 >>>
Note that the range() function can only be used for the list of numbers, and errors will be reported in non numbers.
15.3.5. Use the for loop and iter() function to traverse the list
For example, define the design concept of python, then use the for loop and the iter() function to traverse the list and output each content. The code is as follows:
print("Python Design concept") python = ["grace","to make clear","simple"] for linian in iter(python): print(linian)
The output results are as follows:
Python Design concept grace to make clear simple >>>
15.3.6 use while Loop through the list
Define the list of number, and then iterate through the list through the while loop and output each content. The code is as follows:
number = [1122,2366,4400,5577,8888] i = 0 while i < len(number): print(number[i]) i = i + 1
The operation results are as follows:
1122 2366 4400 5577 8888 >>>
15.4,Add list element
15.4.1. Use in Python append () method to add a list element
We are< Detailed explanation of sequence addition in Python >In the first section, it is said that in Python, Sequence addition Supports two or more of the same type Sequence addition . That is, two or more sequences are connected. However, duplicate elements are not removed. Operation method: sequence addition is realized by "+" operator.
In fact, not only the sequence addition can be realized by the "+" operator, but also the addition of list elements in Python can be realized by the "+" operator. However, this addition method is slower than the python built-in function append() function to add list objects. Usually, when adding list elements, we use the append () method of the list object. List object The append () method is used to add elements to the end of the list. The syntax is as follows:
listname.append(obj)
Where listname is the list name of the element to be added; obj is the object to be added to the end.
For example, define a list of three elements, and then use the append() method to add an element to the end of the list. You can use the following code:
sousuo = ["baidu","sogou","bing"] sousuo.append("Google") print("Updated list:",sousuo)
After executing the code, the result is:
Updated list: ['baidu', 'sogou', 'bing', 'Google'] >>>
15.4.2. Use in Python extend () method to add a list element
As mentioned above, the append() method is used to add list elements at the end of the list. If all the elements of one list are added to another list, the extend () method of the list object is used to add list elements. The syntax of the extend() method is as follows:
listname.extend(seq)
Where, listname is the original list; seq is the list to add. After the statement is executed, the contents of seq will be appended to the list name.
For example, create two lists, and then use the append() method to add the first list to the second list. The specific code is as follows:
s1 = ["abed, I see a silver light","It's suspected to be frost on the ground","look at the bright moon","Bow your head and think of your hometown"] s2 = ["Tang","Li Bai","In the Quiet Night"] s2.extend(s1) print(s2)
The operation result is:
['Tang', 'Li Bai', 'In the Quiet Night', 'abed, I see a silver light', 'It's suspected to be frost on the ground', 'look at the bright moon', 'Bow your head and think of your hometown'] >>>
15.4.3. Use in Python insert () method to add a list element
The append() and extend() methods can only insert elements at the end of the list. If you want to insert elements in the middle of the list, you can use the insert() method.
The syntax format of insert() is as follows:
listname.insert(index , obj)
Where index represents the index value of the specified location. insert() inserts obj into the index element of the listname list.
When inserting a list or tuple, insert() will also treat them as a whole and insert them into the list as an element, which is the same as append().
For example, define a list of three elements, and then use insert() Method to add an element to the middle of the list, you can use the following code:
sousuo = ["baidu","sogou","bing"] sousuo.insert(2,["google","360"]) #Insert the list at position 3, and the whole list is treated as an element print("Updated list:",sousuo)
The execution results are:
Updated list: ['baidu', 'sogou', ['google', '360'], 'bing'] >>>
15.5,Modify list elements
In Python Modify list There are two kinds of elements: one is to modify a single element, and the other is to modify a group of elements. Now? Webmaster Online Explain separately:
15.5.1 modifying a single element in Python
Modifying a single element is very simple. You can assign a value to the element directly. Use index obtain After listing elements, the value of the element is changed through the "=" assignment.
Take the following example:
num = [88, 66, 33, 17, 99, 28, 18] num[2] = 56 #Use positive index num[-3] = -5 #Use negative index print(num)
The operation results are as follows:
[88, 66, 56, 17, -5, 28, 18] >>>
15.5.2. Modify a group of elements in Python
Python supports assigning values to a set of elements through slicing syntax. In this operation, if the step size (step parameter) is not specified, python does not require the number of newly assigned elements to be the same as the number of original elements; This means that the operation can add elements to the list or add elements to the list Delete element.
num = [88, 66, 33, 17, 99, 28, 18] #Modify the value of elements 3 ~ 6 (excluding element 6) num[3:6] = [56,17,-5] print(num)
The operation results are as follows:
[88, 66, 33, 56, 17, -5, 18] >>>
If you assign a value to an empty slice, it is equivalent to inserting a new set of elements:
num = [88, 66, 33, 17, 99, 28, 18] #Insert new element at 5 elements num[4:4] = [56,17,-5] print(num)
Operation results:
[88, 66, 33, 17, 56, 17, -5, 99, 28, 18] >>>
When using slice syntax assignment, Python does not support a single value. For example, the following writing is wrong:
num = [88, 66, 33, 17, 99, 28, 18] #Insert new element at 5 elements num[4:4] = 100 print(num)
Errors are reported as follows:
Traceback (most recent call last): File "D:\Python\Python310\Doc\000.py", line 3, in <module> num[4:4] = 100 TypeError: can only assign an iterable >>>
However, if string assignment is used, Python will automatically convert the string into a sequence, in which each character is an element. See the following code:
s = list("Hello Python") s[6:12] = "XYZ" print(s)
The results are as follows:
['H', 'e', 'l', 'l', 'o', ' ', 'X', 'Y', 'Z'] >>>
When using slice syntax, you can also specify the step size (step parameter), but at this time, the number of assigned new elements is required to be the same as the number of original elements, for example:
num = [88, 66, 33, 17, 99, 28, 18] #The step size is 2 and the values are assigned to the 1st, 3rd and 5th elements num[1: 6: 2] = [55, -55, 59.5] print(num)
The operation result is:
[88, 55, 33, -55, 99, 59.5, 18] >>>
15.6,Divide list elements
Deleting elements in the Python list is mainly divided into the following three scenarios (four methods in total):
a. Delete according to the index of the location of the target element. You can use the del keyword or pop() method.
b. The remove() method provided in the list can be used to delete according to the value of the element itself.
c. Delete all the elements in the list. You can use the information provided in the list clear () method.
Here are four methods for these three scenarios:
15.6.1 del: delete the element according to the index value
del is a keyword in Python, which is specially used to perform deletion. It can not only delete the whole list, but also delete some elements in the list.
We are already< Detailed explanation of the creation and deletion of lists in Python >How to delete the entire list is explained in, so this section only explains how to delete list elements.
del can delete a single element in the list. Its syntax format is:
del listname[index]
Where listname represents the list name and index represents the index value of the element.
For example, define a list of three elements and delete one of them, code Is:
sousuo = ["baidu","sogou","bing"] del sousuo[0] #Delete first, positive index #del sousuo[1] #Delete second #del sousuo[-1] #Delete last, negative index print(sousuo)
The execution results are:
['sogou', 'bing'] >>>
You see, when I wrote the code above, I annotated the third and fourth lines with # code. Otherwise, if I remove the annotation and execute it, there will be no element left, only [].
del can also delete a continuous element in the middle. The format is:
del listname[start : end]
Where, start indicates the start index and end indicates the end index. del deletes the elements from the index start to end, excluding the elements at end.
For example, define a list of 5 elements, delete the 2nd ~ 4th, excluding the 4th, and the code is as follows:
jianzhan = ["Python","html","php","CSS","MySQL"] del jianzhan[1:3] print(jianzhan)
The execution results are:
['Python', 'CSS', 'MySQL'] >>>
Of course, you can also define a list of 5 elements and delete the second to fourth elements, including the fourth. The code is as follows:
jianzhan = ["Python","html","php","CSS","MySQL"] del jianzhan[1:4] print(jianzhan)
The results are as follows:
['Python', 'MySQL'] >>>
15.6.2 pop(): delete elements according to the index value
15.6.2.1 Description: pop() function is used to remove an element in the list (the last element by default) and return the value of the element.
15.6.2.2 syntax: the syntax of pop() method is as follows:
list.pop(-1)
15.6.2.3 parameter: optional parameter. The index value of the list element to be removed cannot exceed the total value of the list length , the default is index=-1, and the last list value is deleted.
15.6.2.4 return value: this method returns the element object removed from the list.
15.6.2.5 example:
sousuo = ["baidu","sogou","bing"] ss = sousuo.pop(1) #Deletes the second element in the list print("Deleted item is :", ss) print("The list is now : ", sousuo)
The operation results are as follows:
Deleted item is : sogou The list is now : ['baidu', 'bing'] >>>
15.6.3. remove(): delete according to the element value
15.6.3.1 Description: the remove() function is used to remove the first matching item of a value in the list. (and the element must be guaranteed to exist.)
15.6.3.2 syntax: list.remove(obj), where list is the list and obj is the object to be removed from the list.
15.6.3.3 return value: this method has no return value, but will remove the first matching item of a value in the list.
15.6.3.4. Example operation of remove() method:
num = [88, 66, 33, 17, 66, 28, 18] num.remove(66) #First delete 66 print(num) num.remove(66) #Second deletion 66 print(num) num.remove(99) #Delete 99 print(num)
The results are as follows:
[88, 33, 17, 66, 28, 18] [88, 33, 17, 28, 18] Traceback (most recent call last): File "D:\Python\Python310\Doc\000.py", line 6, in <module> num.remove(99) #Delete 99 ValueError: list.remove(x): x not in list >>>
For the last deletion, the ValueError exception is caused by the absence of 99. Therefore, when using remove() to delete an element, we'd better judge whether the element exists in advance. The improved code is as follows:
num = [88, 66, 33, 17, 66, 28, 18] num.remove(66) #First delete 66 print(num) num.remove(66) #Second deletion 66 print(num) if num.count(99)>0: #Determine whether the element 99 to be deleted exists num.remove(99) #Specify delete 99 print(num)
The results are as follows:
[88, 33, 17, 66, 28, 18] [88, 33, 17, 28, 18] [88, 33, 17, 28, 18] >>>
Note: the count() method of the list object is used to determine the number of occurrences of the specified element. When the returned result is 0, the element does not exist. For the detailed introduction of the count() method, we will explain it in detail in the next knowledge point "detailed explanation of statistical calculation of lists in Python".
15.6.4. clear(): delete all elements in the list
In Python, clear() is used to delete all elements of the list, that is, to empty the list. See the following code:
s = ["abed, I see a silver light","It's suspected to be frost on the ground","look at the bright moon","Bow your head and think of your hometown"] s.clear() print(s)
The operation result is:
[] >>>
15.7,Statistics and calculation of lists in python
15.7.1. Use the count() method in Python to obtain the number of occurrences of the specified element.
We learned earlier how to calculate the value of a list through the len() function length However, it is neither repeated nor ignored. Today, we will talk about how many times the specified element appears in the list can be obtained by using the count () method of the list object. The syntax format of the numeric type of the count() method is as follows:
listname.count(obj)
Where, listname represents the name of the list; obj represents the object whose occurrence times are to be judged. Here, it refers to exact matching, not part of the element value.
For example, create a sequence list of 8 values, and use the count() method to count the number of occurrences of values. code As follows:
s = [66,88,13,59,66,39,100,59] s1 = s.count(66) s2 = s.count(88) s3 = s.count(99) print("66 Number of occurrences:",s1) print("88 Number of occurrences:",s2) print("99 Number of occurrences:",s3)
The operation results are as follows:
66 Number of occurrences: 2 88 Number of occurrences: 1 99 Number of occurrences: 0 >>>
In addition to counting the numeric list, the count() method can also count the number of occurrences of a string or substring in the string. If there is no, it returns 0. Optional parameters are at the beginning and end of string search.
The syntax is as follows:
str.count(sub,start,end)
In this method, the specific meaning of each parameter is as follows:
str: represents the original string;
sub: indicates the string to retrieve;
Start: Specifies the starting position of retrieval, that is, where to start detection. If it is not specified, it will be retrieved from the beginning by default;
End: Specifies the end position of the retrieval. If it is not specified, it means that the retrieval is until the end.
Column, such as the number of occurrences of "/" in the retrieval string "olzz.com/xuetang/python".
str = "olzz.com/xuetang/python" num = str.count('/') print("'/'Number of occurrences:",num)
The operation result is:
'/'Number of occurrences: 2 >>>
Let's specify the starting address of the string:
str = "olzz.com/xuetang/python" num = str.count('/',1,10) #Specify '/' between characters 2 and 11 print("'/'Number of occurrences:",num)
The operation result is:
'/'Number of occurrences: 1 >>>
15.7.2. Use the index() method in Python to obtain the position where the specified element appears for the first time
In the index() method of Python list object, you can get the position (index) where the specified element appears for the first time in the list. The syntax format of numeric type is as follows:
listname.index(obj)
Parameter Description:
listname: indicates the name of the list.
obj: indicates the object to find (exact match).
Return value: the index value of the first occurrence.
s = [66,88,13,59,66,39,100,59] s1 = s.index(66) s2 = s.index(59) print("66 First occurrence index location:",s1) print("59 First occurrence index location:",s2)
The operation results are as follows:
66 First occurrence: 0 59 First occurrence position: 3 >>>
If the index value is in the list, an exception will be thrown:
s = [66,88,13,59,66,39,100,59] s3 = s.index(77) print("77 First occurrence index location:",s3)
The operation result is:
Traceback (most recent call last): File "D:\Python\Python310\Doc\000.py", line 2, in <module> s3 = s.index(77) ValueError: 77 is not in list >>>
Like the count() method above, the index() method can be used for numeric retrieval or whether the specified string is included. The difference is that when the specified string does not exist, the index() method will throw an exception. (the count() method occurs 0 times, not an exception).
str.index(sub,start,end)
In this method, the specific meaning of each parameter is as follows:
str: represents the original string;
sub: indicates the string to retrieve;
Start: Specifies the starting position of retrieval, that is, where to start detection. If it is not specified, it will be retrieved from the beginning by default;
End: Specifies the end position of the retrieval. If it is not specified, it means that the retrieval is until the end.
Column such as the first occurrence of "/" in the retrieval string "olzz.com/xuetang/python".
str = "olzz.com/xuetang/python" num = str.index('/') print("'/'First occurrence:",num)
The results are as follows:
'/'First occurrence position: 8 >>>
Let's specify the starting address of the string:
str = "olzz.com/xuetang/python" num = str.index('/',1,10) #Specify '/' between characters 2 and 11 print("'/'First occurrence:",num)
Execution results:
'/'First occurrence position: 8 >>>
The execution result is the same, because the location I specified is the same. Now I specify it to the following area and use the negative index:
str = "olzz.com/xuetang/python" num = str.index('/',-10,-1) #Specify '/' between the last and last 10 characters print("'/'First occurrence:",num)
The operation results are as follows:
'/'First occurrence: 16 >>>
The result is from left to right. Because the specified area excludes the eighth one, the 16th one meets the requirements.
15.7.3. Use in Python sum () elements and of the list of function statistics
When talking about the count() method and the index() method, I explained the numerical value and the string separately, because the method of using the numerical value is simpler than the string method.
However, in the sum() function, only numerical values can be counted. The syntax format is as follows:
sum(iterable[, start])
Relevant instructions are as follows:
iterable: iteratable objects, such as lists, tuples, and collections.
start: Specifies the addition parameter. If this value is not set, it defaults to 0.
Examples of summation between the following objects:
>>> sum([0,1,2]) # List summation 3 >>> sum((0,1,2,3),1) # Tuples add 1 after calculating the sum 7 >>> sum([0,1,2,3,4],2) # Add 2 after calculating the sum in the list 12 >>>
Example: the headmaster of a middle school randomly selected the math scores of 10 male students and 10 female students in class 1 of grade 3, and then applied sum() function to calculate the sum of the scores of male and female students. The corresponding codes are as follows:
s1 = [93,95,86,98,99,99,89,100,100,97] #List of math scores of 10 male students s2 = [98,96,86,88,96,100,93,87,95,95] #List of math scores of 10 female students z1 = sum(s1) z2 = sum(s2) print("10 The total score of male students in mathematics is:",z1) print("10 The total score of female students in mathematics is:",z2)
The operation result is:
10 The total score of male students in mathematics is 956 10 The total score of female students in mathematics is 934 >>>
15.8,Sorting lists in python
In the actual development of Python, it is often necessary to sort the list. below Webmaster Online Explain several common methods for sorting lists:
15.8.1 using list objects sort () method.
The list object provides a sort () method to sort the elements in the original list. After sorting, the order of elements in the original list will change. The syntax format of sort() method of list object is as follows:
listname.sort(key=None,reverse=False)
Relevant parameters are described as follows:
listname: indicates the list to be sorted.
Key: specifies a comparison key to extract from each list element. (for example, setting "key=str.lower" means that the sorting is not case sensitive).
reverse: optional parameter. If its value is specified as True, it indicates descending sorting; If it is specified as False, it indicates ascending order. The default is ascending.
For example, the math scores of 10 male students in class 1, grade 3 of a middle school are listed, and then sorted by sort() method, code As follows:
s = [93,95,86,98,99,99,89,100,100,97] print("Original list:",s) s.sort() print("Ascending order:",s) s.sort(reverse=True) print("Descending order:",s)
The results are as follows:
Original list: [93, 95, 86, 98, 99, 99, 89, 100, 100, 97] Ascending order: [86, 89, 93, 95, 97, 98, 99, 99, 100, 100] Descending order: [100, 100, 99, 99, 98, 97, 95, 93, 89, 86] >>>
Using the sort() method, you can sort not only numeric values, but also multiple strings. Sorting strings is case sensitive by default. If you want to be case insensitive, you need to specify its key parameter.
For example, the column definition saves a list of English strings with different uppercase and lowercase, and then sorts them with the sort() method. The code is as follows:
s = ['hello','polly','Lucy','Lily','Han Meimei'] s.sort() print("Case sensitive:",s) s.sort(key=str.lower) print("Case insensitive:",s)
The operation results are as follows:
Case sensitive: ['Han Meimei', 'Lily', 'Lucy', 'hello', 'polly'] Case insensitive: ['Han Meimei', 'hello', 'Lily', 'Lucy', 'polly'] >>>
Note: the sort() method does not support the most Chinese when sorting the list. The sorting result is inconsistent with our common sorting by pinyin or stroke. To sort Chinese content, you need to rewrite the corresponding method instead of using the sort() method directly. For example:
s = ['Zhang San','Li Si','Wang Wu','Li Ming','Jun Yang'] s.sort() print(s)
Operation results:
['Zhang San', 'Li Si', 'Li Ming', 'Jun Yang', 'Wang Wu'] >>>
We can't understand this result at all, so we can't directly use the sort() method to sort the Chinese list.
15.8.2. Use built-in sorted () function.
In Python, a built-in sorted () function is provided to sort the list. After sorting with this function, the element order of the original list remains unchanged. The syntax format of the sorted() function is as follows:
sorted(iterable,key=None,reverse=False)
Relevant parameters are described as follows:
iterable: indicates the list to be sorted.
Key: specifies to extract a comparison key from each list element. (for example, setting "key=str.lower" means that the sorting is not case sensitive).
reverse: optional parameter. If its value is specified as True, it indicates descending sorting; If it is specified as False, it indicates ascending order. The default is ascending.
For example, the math scores of 10 male students in class 1, grade 3 of a middle school are listed, and then sorted by the sorted() function. The code is as follows:
s = [93,95,86,98,99,99,89,100,100,97] s1 = sorted(s) print("Ascending order:",s1) s2 = sorted(s,reverse=True) print("Descending order:",s2) print("Original list:",s)
The operation results are as follows:
Ascending order: [86, 89, 93, 95, 97, 98, 99, 99, 100, 100] Descending order: [100, 100, 99, 99, 98, 97, 95, 93, 89, 86] Original list: [93, 95, 86, 98, 99, 99, 89, 100, 100, 97] >>>
explain:
The sort() method and the sorted() function of a list object do the same thing. There are two different points:
a. The sort() method can only handle the sorting of list type data; The sorted() function can handle sorting of multiple types of data.
b. The sort() method will modify the sorting of the elements of the original list; The sorted() function does not modify the original data, but creates a copy of the original list, but returns a sorted list.
15.8.3 reverse() method is used for reverse sorting.
When we use the sort() method and the sorted() function, we use reverse when dealing with ascending and descending orders.
Reverse means reverse. In fact, there is a special sort, reverse sort. Relevant codes are as follows:
s = [93,95,86,98,99,99,89,100,100,97] python = ["grace","to make clear","simple"] s.reverse() python.reverse() print(s) print(python)
The operation results are as follows:
[97, 100, 100, 89, 99, 99, 98, 86, 95, 93] ['simple', 'to make clear', 'grace'] >>>
In the actual Python development, the reverse() method is used for reverse sorting, which is not mentioned in many tutorials. Because less is used.
15.9,List derivation in python
meaning: List derivation (list reconciliation), also known as list parsing, is that you can quickly generate a list, or generate a list that meets the specified requirements according to a list.
List derivation usually has the following types of syntax formats:
15.9.1 generate a list of values within the specified range. The syntax format is as follows:
list = [Expression for var in range]
Detailed parameter description:
List: indicates the name of the generated list
Expression: an expression that evaluates the elements of a new list
var: loop variable
Range: the range object generated by the range() function
For example, generate a sequence within 10 and an even sequence within 10
a1 = [i for i in range(10)] #Generate a sequence within 10 a2 = [i for i in range(10) if i % 2 == 0] #Generate an even sequence within 10 print(a1) print(a2)
Operation results:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 2, 4, 6, 8] >>>
Let's take another example: the square within 10, code As follows:
s = [i**2 for i in range(10)] print(s)
The operation results are as follows:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>>
The above is relatively simple. Let's do another one to generate a list of 5 random numbers within 10. The code is as follows:
import random #Import random standard library s = [random.randint(0,10) for i in range(5)] print("The five random numbers generated are:",s)
After running, the result is:
The five random numbers generated are: [6, 4, 7, 5, 0] #Multiple runs, the results are different, randomly generated >>>
15.9.2 generate a list of specified requirements according to the list. The syntax is as follows:
newlist = [Expression for var in list]
Detailed parameters are as follows:
newlist: indicates the name of the newly generated list
Expression: an expression that evaluates the elements of a new list
var: variable whose value is the value of each element in the following list
List: the original list used to generate a new list
For example, define the purchase price of a series of goods, and then use the list derivation to generate a fully doubled retail price. The code is as follows:
jinhuo = [5,2,8,6,6,10,15,5] lingshou = [int(i*2) for i in jinhuo] print("Purchase price:",jinhuo) print("Retail price:",lingshou)
The operation results are as follows:
Purchase price: [5, 2, 8, 6, 6, 10, 15, 5] Retail price: [10, 4, 16, 12, 12, 20, 30, 10] >>>
15.9.3 select the qualified elements from the list to form a new list. The syntax format is as follows:
newlist = [Expression for var in list if condition]
Detailed parameters are as follows:
newlist: indicates the name of the newly generated list
Expression: an expression that evaluates the elements of a new list
var: variable whose value is the value of each element in the following list
List: the original list used to generate a new list
Condition: condition expression, used to specify filter conditions
For example, define the purchase price of a series of goods, and then use the list derivation to generate a list with the purchase price less than 10. The code is as follows:
jinhuo = [5,2,8,6,6,10,15,5] s = [i for i in jinhuo if i<10] print("Purchase price:",jinhuo) print("If the purchase price is less than 10:",s)
The operation results are as follows:
Purchase price: [5, 2, 8, 6, 6, 10, 15, 5] If the purchase price is less than 10: [5, 2, 8, 6, 6, 5] >>>
15.10,Creation, access and application of two-dimensional list in python
2D list Concept of:
A two-dimensional list is a list in which other lists are placed as elements of a list, that is, the nesting of lists.
Webmaster Online Warm tip: 2D list is the basis of multidimensional list. 3D list, 4D list and other multidimensional lists will appear in the future.
In Python, there are three common methods to create a two-dimensional list:
15.10.1 directly define the 2D list.
In Python, a two-dimensional list is a list containing a list. That is, each element of a list is a list.
When creating a two-dimensional list, we can directly use the syntax format of the list to define:
listname = [[Element 11,Element 12,Element 13,......,Element 1 n], [Element 21,Element 22,Element 23,......,Element 2 n], ......, [element n1,element n2,element n3,......,element nn]]
The relevant parameters are described as follows:
listname: indicates the name of the list to be generated.
[element 11, element 12, element 13,..., element 1n]: represents the first line of the two-dimensional list (also a list). Where element 11 represents row 1 and column 1, element 12 represents row 1 and column 2, and so on until element 1n represents row 1 and column n.
[element 21, element 22, element 23,..., element 2n]: represents the second line of the two-dimensional list (also a list). Where element 21 represents row 2 and column 1, element 22 represents row 2 and column 2, and so on until element 2n represents row 2 and column n.
[element n1, element n2, element n3,..., element nn]: represents the nth row of the two-dimensional list (also a list). Where element n1 represents the first column of row n, element n2 represents the second column of row n, and so on until element nn represents row N and column n.
For example, define an English score list of three students in class 1, grade 9 of a middle school, code As follows:
cj = [['name','language','mathematics','English'], ['Zhang San',88,98,95], ['Li Si',85,99,91], ['Wang Wu',86,88,89]] print(cj)
Run the above code to create a two-dimensional list as follows:
[['name', 'language', 'mathematics', 'English'], ['Zhang San', 88, 98, 95], ['Li Si', 85, 99, 91], ['Wang Wu', 86, 88, 89]] >>>
15.10.2. Create a two-dimensional list using a nested for loop.
In Python, a nested for loop can be used to create a two-dimensional list. For example, to create a two-dimensional list with 5 rows and 5 columns, you can use the following code:
s = [] # Create an empty list for i in range(5): # Create a 5-Row list (rows) s.append([]) # Add an empty list to an empty list for j in range(5): # Loop each element (column) of each row s[i].append(j) # Add element to inner list print(s) # Output list
Run the above code to create a two-dimensional list as follows:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] >>>
15.10.3 create a two-dimensional list using list derivation.
We were just at the last knowledge point< Detailed explanation of list derivation in python >Learned list derivation. List derivation is to quickly generate a list, or generate a list that meets the specified requirements according to a list.
Here, we can also use list derivation to create two-dimensional lists. It is the recommended method, and the syntax is simple.
For example, use the list derivation method to create a two-dimensional list with 5 rows and 5 columns. The code is as follows:
s = [[j for j in range(5)] for i in range(5)] print(s)
Execute the above code to create a two-dimensional list. The results are as follows:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] >>>
15.10.4 access to 2D list
After creating a two-dimensional list, we can access the list elements through the following syntax:
listname[Index 1][Index 2]
The relevant parameters are described as follows:
listname: indicates the name of the list
Index 1: rows in the list. The index value starts from 0, i.e. the first row has an index of 0. (index is also called subscript, and index 1 is also called subscript 1)
Index 2: columns in the list. The index value starts from 0, that is, the first column has an index of 0. (index is also called subscript, and index 2 is also called subscript 2)
For example, to define a two-dimensional list and access its first row and fifth column, you can use the following code: listname[0,4]
s = [[j for j in range(5)] for i in range(5)] # Define a two-dimensional list of 5 rows and 5 columns print("5 The list of row 5 and column is:",s) # Output 2D list print("The first row and the fifth column are:",s[0][4]) # Output the elements in row 1 and column 5
The operation result is:
5 The list of row 5 and column is: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] Row 1 and column 5 are: 4 >>>
15.10.5 application of two-dimensional list
Using a two-dimensional list to output the ancient poem "thinking at quiet night" in different formats
--Horizontal plate--
abed, I see a silver light
It's suspected to be frost on the ground
look at the bright moon
Bow your head and think of your hometown
--Vertical plate--
Low lift doubt bed
The head is the front
Si Wang Di Ming
Last month of the Ming Dynasty
Township moon frost light
stationmaster Online warm reminder: the horizontal version is read from left to right, and the vertical version is read from right to left.
We are IDLE A new file is created in. In this file, four strings are defined as the verses of Jingyesi, and then a two-dimensional list is defined. The nested for loop is used to output the ancient poems in horizontal version, and then the two-dimensional list is arranged in reverse order. Finally, the nested for loop is used to output the ancient poems in vertical version. The code is as follows:
str1 = 'abed, I see a silver light' str2 = 'It's suspected to be frost on the ground' str3 = 'look at the bright moon' str4 = 'Bow your head and think of your hometown' verse = [list(str1), list(str2), list(str3), list(str4)] # Define a 2D list print('\n-- Horizontal plate --\n') for i in range(4): # Cycle every line of ancient poetry for j in range(5): # Loop each word (column) of each row if j == 4: # If it is the last word in a line print(verse[i][j]) # Wrap output else: print(verse[i][j], end='') # No newline output verse.reverse() # Arrange the list in reverse order print('\n-- Vertical plate --\n') for i in range(5): # Loop each word (column) of each row for j in range(4): # Loop the first row after the new reverse order if j == 3: # If it's the last line print(verse[j][i]) # Wrap output else: print(verse[j][i], end='') # No newline output
The operation results are as follows:
-- Horizontal plate -- abed, I see a silver light It's suspected to be frost on the ground look at the bright moon Bow your head and think of your hometown -- Vertical plate -- Low lift doubt bed The head is the front Si Wang Di Ming Last month of the Ming Dynasty Township moon frost light >>>
Principle analysis:
15.10.5.1 first convert the string of each line of ancient poetry into a list using the list() function. The list code is as follows:
[['Bed','front','bright','month','light'], ['Doubt','yes','land','upper','frost'], ['lift','head','at','bright','month'], ['low','head','thinking','so','country']]
15.10.5.2. The reverse() method of the list object is used to reverse sort the list, moving the last to the first, the penultimate to the second, and so on. The code is as follows:
[['low', 'head', 'thinking', 'so', 'country'], ['lift', 'head', 'at', 'bright', 'month'], ['Doubt', 'yes', 'land', 'upper', 'frost'], ['Bed', 'front', 'bright', 'month', 'light']]
15.10.5.3 the horizontal version is printed by line, while the vertical version is printed by column. The printing by column is as follows:
Low lift doubt bed The head is the front Si Wang Di Ming Hence the name last month Township moon frost light
See, we can't read smoothly, and the column printed "raise the doubt bed low, the head is in front, think and look clearly, so it's called last month, the frost light of the township moon" is exactly the vertical printed poem we want. Vertical is written from right to left. Reading also starts from the right, which is the poem we want.
In fact, the above 10 points can only be explained in 10 articles. If only one class is concerned, it takes three or five days to write a tutorial. Moreover, when learning, it may not be finished in one day. It is estimated that it can only be finished in three or five days.
Next section Preview: Zero foundation Python complete self-study tutorial 16: tuples in Python
Related reading:
Directory summary of zero basic Python complete self-study tutorial
Webmaster encyclopedia entry: Python