"Learning Python with You Hand in Hand" 20-List

In the previous article "Learning Python with You Hand in Hand " 19-Summary of the first stage , we summarized the content of the previous stage and applied it by writing a more complex program. At the same time, I also left a question for everyone, that is, as the "designer" of the game, how can I guess the right one at a time?

In fact, just let us see the four-digit number generated by the computer during the running of the program. The method is to "print" the number after the computer generates the number. As a program designer, do you feel proud? So we can imagine that in some large games, if the programmer wants to leave a back door for himself, increase combat power or even invincible, it is not a difficult task.

The end of the first phase of learning, starting today, we will start a new journey. In this stage, we will learn the various data types of Python and the usage of custom functions. In this article, we will give a formal introduction to the "list" that we have been exposed to many times before.

1. The definition of the list

List is the most commonly used data structure in Python. It is a sequence of data enclosed in a pair of square brackets. As we have touched before, the elements in the sequence can be data types such as numbers, Booleans, strings, lists, variables, etc., or lists that include the above elements, forming multiple levels of nesting. At the same time, the printed result of the list is also a list enclosed in square brackets.

In [1]: list1 = [1, 'a']    # 列表元素是数字和字符串
        list
Out[1]: [1, 'a']
​
In [2]: list2 = [1, 'a', list1]   # 列表元素是数字、字符串和变量,同时变量又是一个列表,形成嵌套
        list2
Out[2]: [1, 'a', [1, 'a']]

One thing to note here is that the data types that can be used as list elements are not only numbers, booleans, strings, lists, variables, but also tuples, dictionaries, sets and other data types that you will learn later, but because they have not been introduced yet , So when defining and exemplifying the list, only take what we have learned as an example (the same below). If you are interested, you can wait for us to learn other data types and return to test whether these data types can be used as elements of the list.

2. Index and slice of the list

The common operations of lists can be called "addition, deletion, modification, and check". Indexing and slicing are the "checks" and one of the most important operation methods for lists. The method of indexing and slicing the list is exactly the same as that of the string, except that the string uses each character as the operation object, and the list uses each data element as the operation object.

In [3]: string = 'Python'
        list = ['P', 'y', 't', 'h', 'o', 'n']
​
In [4]: string[3]
Out[4]: 'h'
​
In [5]: list[3]   # 索引的结果是对应的元素
Out[5]: 'h'
​
In [6]: string[2:5]
Out[6]: 'tho'
​
In [7]: list[2:5]   # 切片的结果是对应元素组成的列表
Out[7]: ['t', 'h', 'o']
​
In [8]: list[3:4]   # 切片的结果即使只有一个元素,结果也是列表
Out[8]: ['h']
​
In [9]: list[3:3]   # 甚至切片的结果为空,结果也是一个空列表
Out[9]: []

Therefore, for the method of indexing and slicing lists, I will not give examples one by one. You can refer to "Learning Python with You" 7-Indexing of Strings , "Learning Python with You" 8-Slicing of Strings The contents of the two articles try to list indexing and slicing methods. Especially for the case where the slicing parameters are more complicated, I hope everyone will try them one by one to ensure that they can be fully mastered, and lay the foundation for the flexible use of the important data structure of the list later.

3. Modification of the list

The "addition, deletion, and modification" of the list can be collectively referred to as the update of the list, which is also a unique feature of the list. For example, the "tuples" we will introduce in our next article cannot be updated.

There are two cases of list modification.

One is to modify the "element" after the list index. It is to directly replace this element with the modified element. This element can be various data types such as numbers, booleans, strings, lists, or variables with values ​​of these data types.

In [10]: list3 = [0, 1, 2, 3, 4, 5]
         list3[0] = 'Python'   # 索引后的元素替换成字符串
         list3[1] = 10   # 索引后的元素替换成数字
         list3[2] = ['a', 'b']   # 索引后的元素替换成列表,形成嵌套
         list3[3] = list   # 索引后的元素替换成变量
         list3
Out[10]: ['Python', 10, ['a', 'b'], ['P', 'y', 't', 'h', 'o', 'n'], 4, 5]

The second is to modify the "list" after the list is sliced. At this point, the modified object needs to be a data type that can be "traversed", such as a string, a list, or a variable whose value is these data types. The replacement process is equivalent to picking out the list elements of the slice part, and at the same time splitting the modified object into the smallest unit (each character of the string, each element of the list) as the elements of the list, and replacing it to the selected The position of the down element. The modification in this case does not require the same number of elements before and after modification. But because numbers or boolean values ​​cannot be "traversed", they cannot be used as replacement values ​​in this case.

In [11]: list4 = [0, 1, 2, 3, 4, 5]
         list4[2:3] = ['a', 'b']   # 对比上例中对于第三个元素的修改,此时不是将切片后的元素替换成列表,而是将切片后的元素替换成新的列表中的元素
         list4
Out[11]: [0, 1, 'a', 'b', 3, 4, 5]
​
In [12]: list5 = [0, 1, 2, 3, 4, 5]
         list5[:-1] = ['a', 'b']   # 替换前后的元素个数可以不同
         list5
Out[12]: ['a', 'b', 5]
​
In [13]: list6 = [0, 1, 2, 3, 4, 5]
         list6[2:4] = []   # 替换为空列表,相当于删除列表中指定位置的元素
         list6
Out[13]: [0, 1, 4, 5]
​
In [14]: list7 = [0, 1, 2, 3, 4, 5]
         list7[-1:] = 1   # 因为数据不能够被“遍历”,替换为数字时报错
         list7
Out[14]: ---------------------------------------------------------------------------
         TypeError                                 Traceback (most recent call last)
         <ipython-input-53-3b2d30b5da1c> in <module>
               1 list7 = [0, 1, 2, 3, 4, 5]
         ----> 2 list7[-1:] = 1   # 替换为非列表的数据元素报错
               3 list7
               
         TypeError: can only assign an iterable
         
In [15]: list8 = [0, 1, 2, 3, 4, 5]
         list8[-3:] = 'Python'   # 可以替换为字符串,但会先将字符串'Python'拆分到最小单元,再进行替换
         list8
Out[15]: [0, 1, 2, 'P', 'y', 't', 'h', 'o', 'n']
​
In [16]: list9 = [0, 1, 2, 3, 4, 5]
         list9[3:5] = ['P', 'y', 't', 'h', 'o', 'n']   # 可以替换为列表,也是将列表拆分成多个元素,再进行替换
         list9
Out[16]: [0, 1, 2, 'P', 'y', 't', 'h', 'o', 'n', 5]

Because the data type to be modified after slicing can be "traversed", we can quickly think of for loop statements. That is, the data type to be replaced after slicing is consistent with the data type that can be traversed by the for loop. Although the two knowledge points that seem to be completely unconnected, they are linked together because of the same "traversal" requirement.

So say a few more words here. A great programming language is not just a patchwork of knowledge points or grammatical rules. At its inner or higher level, there will be more universal rules and logic.

Not only the point just mentioned, including the index and slicing of lists and strings that we learned before, the same rules and parameter system are used. Many data types to be learned later are even more used in data analysis. The complex multi-dimensional data structure also follows the same indexing and slicing principles.

This requires that when we learn Python, one is to thoroughly understand and understand the basic concepts, and the other is to link the internal connections between different knowledge points with the same rule system to help us deepen our understanding and improve learning efficiency. . This is also the reason why in the "Learning Python with You Hand in Hand" series of articles, various situations are often listed for a small knowledge point, so that everyone can thoroughly understand the reason. Although it seems to have wasted some time and learning is boring, when we connect several knowledge points, we will find that this method is more efficient and valuable.

4. The increase of list elements

In the introduction to the modification of the above list, a method of adding list elements has actually been included. That is, through modification after slicing, adding elements in the "any" position of the list is indirectly realized. But the most commonly used method of adding list elements is the append() method, which is used to add new elements or objects at the "end" of the list.

In "Learning Python with You" 10-String Functions , we talked about the difference between "function" and "method". In short, the object of the function is written in parentheses, while the object of the method is written In front of the name. Because append() is a method, the name list of the list object to be operated on should be written before append, and the element or object object to be added at the end of the list is written in parentheses.

list.append(object)

The object parameter in the append() method can be a number, a boolean value, a string, a list, or a variable, etc., but it can only have one parameter, that is, one operation can only add one element to the back of the list.

In [17]: list10 = [0, 1, 2, 3, 4, 5]
         list10.append(6)   # 先在列表末尾增加数字6
         list10.append('78')   # 之后在更新后的列表后面增加字符串'7'
         list10.append([9, 10])   # 最后再在更新后的列表增加列表[8, 9],此时的参数也只有一个
         list10
Out[17]: [0, 1, 2, 3, 4, 5, 6, '78', [9, 10]]
​
In [18]: list11 = [0, 1, 2, 3, 4, 5]
         list11.extend(1, 3)   # 当参数超过一个时报错
         list11
Out[18]: ---------------------------------------------------------------------------
         TypeError                                 Traceback (most recent call last)
         <ipython-input-14-8845285907af> in <module>
               1 list11 = [0, 1, 2, 3, 4, 5]
         ----> 2 list11.extend(1, 3)
               3 list11
               
         TypeError: extend() takes exactly one argument (2 given)

In addition to the append() method, there is also extend() to add elements to the end of the list. The extend() method can only have one parameter in the parentheses. Unlike append(), the parameter of extend() is required to be "traversed" (similar to the modification of the list after slicing), and then the parameters will be changed first The data in is split into the smallest units, and multiple elements are added at the end of the list at once. Data types such as numbers and booleans cannot be "traversed", so they cannot be used as parameters of extend().

list.extend(object)

In [19]: list12 = [0, 1, 2, 3, 4, 5]
         list12.extend('78')   # 先将字符串'78'拆分成'7'和'8',再添加到列表末尾
         list12.extend([9, 10])   # 之后将列表拆分成多个元素,在刚才更新后的列表后进行添加
         list12
Out[19]: [0, 1, 2, 3, 4, 5, '7', '8', 9, 10]
​
In [20]: list13 = [0, 1, 2, 3, 4, 5]
         list13.extend([6, 7], '8')   # 当参数超过一个时报错
         list13
Out[20]: ---------------------------------------------------------------------------
         TypeError                                 Traceback (most recent call last)
         <ipython-input-20-13fee015b48c> in <module>
               1 list13 = [0, 1, 2, 3, 4, 5]
         ----> 2 list13.extend([6, 7], '8')   # 当参数超过一个时报错
               3 list13
               
         TypeError: extend() takes exactly one argument (2 given)
         
In [21]: list14 = [0, 1, 2, 3, 4, 5]
         list14.extend(6)   # 当参数为一个不可被“遍历”的数据类型时报错
         list14
Out[21]: ---------------------------------------------------------------------------
         TypeError                                 Traceback (most recent call last)
         <ipython-input-23-f49cfc1155db> in <module>
               1 list14 = [0, 1, 2, 3, 4, 5]
         ----> 2 list14.extend(6)   # 当参数为一个不可被“遍历”的数据类型时报错
               3 list14
               
         TypeError: 'int' object is not iterable

5. Deletion of list elements

In the introduction to the modification of the list above, a method of deleting list elements has also been included. It is to indirectly realize the purpose of deleting the element in the "any" position of the list by modifying it into an "empty list" after slicing. But the most commonly used method to delete list elements is the del statement, which is used to directly delete the index or slice of the list.

del list[a:b]

In [22]: list15 = [0, 1, 2, 3, 4, 5]
         del list15[2]   # 索引后删除一个元素
         list15
Out[22]: [0, 1, 3, 4, 5]
​
In [23]: list16 = [0, 1, 2, 3, 4, 5]
         del list16[2:4]   # 切片后删除多个元素
         list16
Out[23]: [0, 1, 4, 5]

In addition to the del statement, there is also a remove() method to delete list elements. It is a method of deleting the first matching item in the list that matches a certain value. In other words, del is to delete according to the position of the element in the list, and remove() is to delete according to the element value. Similarly, remove() can only have one parameter.

list.remove(object)

In [24]: list17 = [0, 1, 2, 3, 4, 5, 4, 3, 2, 1]
         list17.remove(3)   # 只删除与参数值相同的第一个匹配项
         list17
Out[24]: [0, 1, 2, 4, 5, 4, 3, 2, 1]
​
In [25]: list18 = [0, [1, 2], 3, 4, 5, 4, 3, [1, 2]]
         list18.remove([1, 2])   # 只删除与参数值相同的第一个匹配项
         list18
Out[25]: [0, 3, 4, 5, 4, 3, [1, 2]]

6, the calculation of the list

The calculation of the list is actually what I just said. It follows the higher-level uniform rules of Python and is consistent with the calculation of strings, rather than the specific syntax requirements of the list.

In [26]: [1, 2, 3] + [4, 5, 6]   # 与字符串一样,+也是拼接运算
Out[26]: [1, 2, 3, 4, 5, 6]
​
In [27]: [1, 2, 3] * 3   # *也是重复输出
Out[27]: [1, 2, 3, 1, 2, 3, 1, 2, 3]
​
In [28]: [1, 2, 3] == [1, 2, 3]   # 比较运算,要完全相同
Out[28]: True
​
In [29]: [1, 2, 3] != [1, 2, 3]   # 比较运算
Out[29]: False
​
In [30]: [2, 2, 3] > [1, 2, 2, 4]   # 比较运算,只比较第一个元素
Out[30]: True
​
In [31]: 1 in [1, 2, 3]   # 成员运算
Out[31]: True
​
In [32]: 1 not in [1, 2, 3]   # 成员运算
Out[32]: False
​
In [33]: [1, 2, 3] is [1, 2, 3]   # 身份运算,值相同,但内存地址不同,具体请参见《手把手陪您学Python》13——运算
Out[33]: False

7, the function of the list

The following table enumerates four commonly used list functions. Except for the fourth one, which we don’t use yet, other functions can be applied to our programs. In particular, the function len(), which counts the number of elements in a list, is something we will often use in the future, and it is often used in conjunction with a for loop.

Serial number

function

effect

1

flax (list)

Returns the number of list elements

2

max(list)

Returns the maximum value of the list element

3

min(list)

Returns the minimum value of the list element

4

list(seq)

Convert tuples to lists

In [34]: day_lst = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
         for i in range(len(day_lst)):
             print("每周的第{}天是{}。".format(i+1,day_lst[i]))
Out[34]: 每周的第1天是星期日。
         每周的第2天是星期一。
         每周的第3天是星期二。
         每周的第4天是星期三。
         每周的第5天是星期四。
         每周的第6天是星期五。
         每周的第7天是星期六。
         
In [35]: list19 = [1, 2, 3]
         print("由数字组成的列表,最大值和最小值是按照ASCII码从小到大排序的,因此list19的最大值是{},最小值是{}。".format(max(list19), min(list19)))
Out[35]: 由数字组成的列表,最大值和最小值是按照ASCII码排序的,因此list19的最大值是3,最小值是1。
​
In [36]: list20 = ['a', 'b', 'c']
         print("由字符串组成的列表,最大值和最小值也是按照ASCII码从小到大排序的,因此list20的最大值是{},最小值是{}。".format(max(list20), min(list20)))
Out[36]: 由字符串组成的列表,最大值和最小值也是按照ASCII码从小到大排序的,因此list20的最大值是c,最小值是a。
​
In [37]: list21 = ['手', '把', '手', '陪', '您', '学']
         print("由中文组成的列表,最大值和最小值是按照unicode从小到大排序的,因此list21的最大值是{},最小值是{}。".format(max(list21), min(list21)))
Out[37]: 由中文组成的列表,最大值和最小值是按照unicode从小到大排序的,因此list21的最大值是陪,最小值是a。
​
In [38]: list22 = ['手', '把', '手', '陪', '您', '学', 'a', 'b', 'c']
         print("字符串只能和字符串比较,因此list22的最大值是{},最小值是{}。".format(max(list22), min(list22)))
Out[38]: 字符串只能和字符串比较,因此list22的最大值是陪,最小值是a。
​
In [39]: list23 = ['手', '把', '手', '陪', '您', '学', 1, 2, 3]
         max(list23)   # 字符串和数字不能混合比较
Out[39]: ---------------------------------------------------------------------------
         TypeError                                 Traceback (most recent call last)
         <ipython-input-30-bd7a314f9f23> in <module>
               1 list23 = ['手', '把', '手', '陪', '您', '学', 1, 2, 3]
         ----> 2 max(list23)
         
         TypeError: '>' not supported between instances of 'int' and 'str'
​
In [40]: list24 = [[1, 2, 3], [2, 2, 1]]
         print("列表间的比较也是根据列表中第一个字符的值进行比较,因此list24的最大值是{},最小值是{}。".format(max(list24), min(list24)))
Out[40]: 列表间的比较也是根据列表中第一个字符的值进行比较,因此list24的最大值是[2, 2, 1],最小值是[1, 2, 3]。

8. List method

Just now we have learned the two list methods of append() and remove(), which are adding list elements and deleting list elements respectively. The following table also lists nine other list methods, and examples of the more commonly used methods will be given later. For other methods that have not been illustrated, please try it yourself. I believe you can do it after learning Python for so long.

 

Serial number

method

method

1

list.append(obj)

Add a new object at the end of the list

2

list.count(obj)

Count the number of times an element appears in the list

3

list.extend(seq)

Append multiple values ​​from another sequence at the end of the list at once (expand the original list with the new list)

4

list.index(obj)

Find the index position of the first match of a value from the list

5

list.insert(index, obj)

Insert object into list

6

list.pop([index=-1])

Remove an element from the list (the last element by default), and return the value of the element

7

list.remove(obj)

Remove the first occurrence of a value in the list

8

list.reverse()

Reverse the elements in the list

9

list.sort(cmp=None, key=None, reverse=False)

Sort the original list

10

list.clear()

clear the list

11

list.copy()

Copy list

In [41]: list25 = ['《', '手', '把', '手', '陪', '您', '学', 'P', 'y', 't', 'h', 'o', 'n', '》']
         list25.sort()   # 与比较运算一样,同样类型的元素内部才能够排序
         list25
Out[41]: ['P', 'h', 'n', 'o', 't', 'y', '《', '》', '学', '您', '手', '手', '把', '陪']
​
In [42]: list26 = ['《', '手', '把', '手', '陪', '您', '学', 'P', 'y', 't', 'h', 'o', 'n', '》']
         list26.index('P')
Out[42]: 7
​
In [43]: list27 = [1, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3]
         list27.count(3)
Out[43]: 3
​
In [44]: list28 = [0, 1, 2, 3, 4, 5]
         list28.insert(3, 'Python')
         list28
Out[44]: [0, 1, 2, 'Python', 3, 4, 5]
​
In [45]: list29 = [0, 1, 2, 3, 4, 5]
         list29.pop(3)
         list29
Out[45]: [0, 1, 2, 4, 5]

The above is the introduction to the related content of the Python list. Although it seems to have a lot of content, we will introduce it all with one article. This is because many of the contents of strings, operations, etc. introduced before are applicable to lists, which saves us a lot of effort in learning lists, and we don’t need to learn from basic concepts and can understand through a few examples. Very clear.

It can be said that this is the result of our learning! And the more you learn later, this kind of experience will become stronger and stronger, so everyone must understand all the content of the first stage, so that we can learn and apply better later.

The next article will introduce you to tuples, because tuples can be regarded as lists that are not allowed to be modified, so many properties and methods are exactly the same as lists, so learning will be very easy, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

For Fans: Follow the "also said Python" public account, reply "Hand 20", you can download the example sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/100020403