Home >Backend Development >Python Tutorial >Detailed explanation of the use of lists and tuples in Python learning
This article brings you relevant knowledge about Python, which mainly introduces detailed explanations about the use of lists and tuples, including list declaration syntax, list reading, and list operations. , basic knowledge and operations of elements, etc. Let’s take a look at them together. I hope it will be helpful to everyone.
[Related recommendations: Python3 video tutorial]
If you are talking about Python Looking for the best data type in the language, it is undoubtedly the list. If I want to recommend one, then I choose the tuple. Our focus in this blog will be on the list. The tuple can be regarded as a list that cannot be modified. So as a gift just study.
List is a very flexible data structure that can make up for many shortcomings of the previous string type.
Before formal learning, you need to remember two English words, list and tuple.
First look at the list definition:
A list is a variable sequence and a container that can store any data type. Use square brackets ([]
) represents the start and end. The internal elements are separated by English commas (,
). Each element can be called a project, and each element has an index, also known as is the subscript.
To declare a list, you can refer to the following formats.
Use empty brackets [] to declare an empty list
my_list = [] print(my_list)
Declare a list containing one element
my_list = [1] print(my_list)
Declaring a list containing multiple elements
my_list = [1,2] print(my_list)
Declaring a list containing multiple elements of different data types
my_list = [1,'a',True] print(my_list)
Declaring a list containing a list
my_list = [1,['a'],[True,1,1]] print(my_list)
The most important concept in reading lists is the subscript, also called position or index. The subscripts start counting from 0, that is, the index of the first element in the list is 0. For example, the following code reads the number 2.
my_list = [1,2,3,4,5] print(my_list[1]) # 数字2所在的下标为1
A list is a dynamic container that supports operations such as adding, deleting, modifying, querying, and merging its elements. All methods used are dictionary objects. Basically The operation method names are as follows:
append()
: Append elements to the end; extend()
: Append the list to the end , can also be understood as merging two lists; insert()
: Insert an element at the specified position; copy()
: Copy the list ; clear()
: Clear the list; count()
: Count the number of specified elements in the list; pop()
: Delete and return the element corresponding to the specified subscript; remove()
: Remove the specified element from the list; index()
: Get the index of the specified element; reverse()
: Reverse the element; sort ()
: Sort list elements. List element addition method
From the above list, you can see that the list appends elements. There are two ways to achieve it. One is to use append()
method, the second is to use the insert()
method, the sample code is as follows:
my_list = [1,2,3,4,5] my_list.append(888) my_list.insert(1,666) print(my_list)
Compare the differences between the above two methods, you can seeappend()
can only append elements at the end of the list, while the insert()
method can insert elements at any position, that is, the first one of the insert()
method The parameter is the index, indicating the insertion position.
List element search method
To find an element in the list, use the index()
method. The syntax format of this method is as follows Display:
my_list.index(value,[start[,stop]])
where my_list
is the list of targets to be found, value
represents the value to be found, start
and stop
is an optional parameter, indicating the index value to start searching and the index value to end searching. When an element is found, this method will return the index position of the first element found. For example, the following code will return 3
.
my_list = [1,2,3,4,5] ret = my_list.index(4) print(ret)
If this method does not find an element in the target list, an error will be reported with the error type ValueError
.
In addition to the index()
method, reading the list is also a method of element search. For example, reading the element with subscript 2, the code is as follows:
my_list = [1,2,3,4,5] ret = my_list[2] print(ret)
Alright Use the member operator in
to judge the list. More knowledge about the member operator will be explained in detail later when the operators are summarized. The following code returns True
, which means the number 2 is in the list.
my_list = [1,2,3,4,5] ret = 2 in my_list print(ret)
There is another important knowledge point in the list, that is, list slicing. To learn this knowledge point, you need to firmly master the syntax related to reading lists by index. The syntax format of slicing is as follows:
my_list = [1,2,3,4,5] ret = my_list[1:3:2] print(ret)
You can see the second line of code above. Based on the rules for reading the original list, the format changes to [1:3:2]
. Convert it to Chinese grammar and the instructions are as follows:
my_list[起始索引:结束索引:步长]
使用切片的时候,英文冒号不能缺少,起始索引为必选项,结束索引和步长为可选项。
如果理解困难,最好的办法就是反复用代码校验。
# 缺省结束索引,默认获取到列表结尾元素 my_list = [1,2,3,4,5,6,7,8,9,10] ret = my_list[1:] print(ret) # 输出 [2, 3, 4, 5, 6, 7, 8, 9, 10] # 缺少步长,默认按照索引+1解决,同时不包含结束索引代表的元素 my_list = [1,2,3,4,5,6,7,8,9,10] ret = my_list[1:5] print(ret) # 输出 [2, 3, 4, 5] # 步长设置为2,表示索引每次+2 my_list = [1,2,3,4,5,6,7,8,9,10] ret = my_list[1:6:2] print(ret) # 输出 [2, 4, 6]
上述代码如何理解已经在注释中进行说明,重点要掌握的切片知识点整理如下:
一首打油诗送给大家~
切片不能丢冒号 结束步长可不要 默认索引都加一 左闭右开要牢记
前文已经掌握了列表的读取,将读取到的元素重新赋值就是列表的修改,例如下述代码。
my_list = [1,2,3,4,5,6,7,8,9,10] my_list[1] = 666 print(my_list)
列表元素删除 在 Python 中,提出了多种列表元素删除的方式,本小节学习三个列表元素删除的方法,即 clear()
,pop()
,remove()
,除此之外还可以使用 del()
函数对列表元素进行删除。
my_list = [1,2,3,4,5,6,7,8,9,10] my_list[1] = 666 my_list.clear() # 列表清空 print(my_list)
使用 pop()
方法删除列表元素,默认从尾部删除,并返回被删除的元素。
my_list = [1,2,3,4,5,6,7,8,9,10] my_list[1] = 666 ret = my_list.pop() print(my_list) # 删除最后一项 print(ret) # 返回被删除的元素
pop()
方法中可以传递一个 index
值,该值表示下标值,即删除指定位置的元素,与之对应的是 remove()
方法的参数,该值表示待删除的目标元素,例如在列表中删除元素 5,使用的代码如下:
my_list = [1,2,3,4,5,6,7,8,9,10] my_list[1] = 666 ret = my_list.remove(5) print(my_list) print(ret)
测试之后,可以发现 remove()
方法无返回值,并且该方法只删除第一个匹配到的元素,也就是当列表中有多个目标元素时,只有最先匹配到的元素被删除。
del()
函数可以删除列表中指定元素,也可以直接删除列表对象,代码如下:
# 删除索引位置为5的元素 my_list = [1,2,3,4,5,6,7,8,9,10] my_list[1] = 666 del(my_list[5]) print(my_list) # 删除整个列表对象 my_list = [1,2,3,4,5,6,7,8,9,10] my_list[1] = 666 del my_list print(my_list)
使用 extend()
方法可以将列表进行合并:
my_list1 = [1,2,3] my_list2 = [666,777,888] my_list1.extend([666,777,888]) print(my_list1)
注意 extend()
方法不会生成新的列表。
列表合并也可以使用加号(+
) 实现,该语法会产生一个新的列表。
my_list1 = [1,2,3] my_list2 = [666,777,888] my_list = my_list1 + my_list2 print(my_list)
列表排序用到的方法是 sort()
,该方法默认按照 ASCII 进行增序或者减序排列,测试代码如下所示:
my_list = [4,1,2,6,7,3,8,12,10] my_list.sort() print(my_list)
在 sort()
方法中也有 2 个参数,格式如下:
my_list.sort(key=None,reverse=False)
参数 key
为可选参数,可以传入一个函数名,该函数会作用与列表中的每一项元素,例如将列表中每一项元素都转换为小写字母。
my_list = ['ABC','CDS','Juejin','YUE'] my_list.sort(key=str.lower) print(my_list)
sort()
方法会对原列表进行排序,如果想生成一个新列表,可以使用 sorted()
函数,代码如下:
my_list = ['ABC','CDS','Juejin','YUE'] ret = sorted(my_list) print(ret)
除此之外,还可以使用 reverse()
方法。
my_list = ['ABC','CDS','Juejin','YUE'] my_list.reverse() print(my_list)
元组定义与列表基本一致,只需要做好如下区分即可。
()
)表示。再次进行简单总结:
元组是不可变序列,也是可以包含任意数据类型的容器,用小括号(()
)表示,元素之间用逗号(,
)分隔 。一定要注意的就是不可变序列,不可变的含义是不能对元组进行增加,修改,删除,位置变换等操作。
声明一个元组
my_tuple = () print(my_tuple) print(type(my_tuple))
声明一个只包含 1 个值的元组,要求必须带一个逗号,否则会按照整数处理。
my_tuple = (1,) print(my_tuple) print(type(my_tuple))
声明包含多个值的元组:
my_tuple = (1,2,3,4,5,6,[1]) print(my_tuple) print(type(my_tuple))
由于元组对象的方法使用与列表一致,接下来仅对元组进行罗列。
count()
:统计元组中元素个数;index()
:返回指定元素的下标。其余可作用于元组的内置函数如下所示:
len()
:获取元组元素个数;max()
:返回元组中最大值;min()
:返回最小值;tuple()
:将列表转换为元组;type()
:返回对象类型;del()
:删除整个元组对象,注意不能删除元组内元素;sum()
:求和。【相关推荐:Python3视频教程 】
The above is the detailed content of Detailed explanation of the use of lists and tuples in Python learning. For more information, please follow other related articles on the PHP Chinese website!