一、List的简介
Python中的List是一个有序的集合,可以保存任意类型的数据,包括整数、字符串和其他对象的引用。List通过方括号[]来表示,其中元素之间用逗号分隔。
# 创建一个包含不同数据类型的List list1 = [1, 2, "three", 4.0, ["five", 6]] # 访问List中的元素 print(list1[0]) # 输出 1 print(list1[2]) # 输出 three print(list1[-1][0]) # 输出 five
需要注意的是,List中的元素可以是任何类型的数据,甚至可以包含另一个List或其他数据类型。同时,List是一个可变的数据类型,也就是说它的值可以在程序执行过程中被修改。
二、创建List的方式
创建List的方式有两种:通过[]创建空List,通过list()从已有的序列或其他数据类型转换而来。
# 创建空的List list1 = [] # 或者 list1 = list() # 从已有的序列转换而来 str1 = "Hello, world!" list2 = list(str1) print(list2) # 输出 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'] # 从其他数据类型转换而来 tuple1 = (1, 2, 3) list3 = list(tuple1) print(list3) # 输出 [1, 2, 3]
三、 List的基本操作
1. 修改List
List是可变数据类型,因此可以对其进行修改。可以使用索引来直接修改List中的元素,也可以使用切片操作来替换List中的部分元素。
# 修改List中的元素 list1 = ['a', 'b', 'c', 'd'] list1[1] = 'e' print(list1) # 输出 ['a', 'e', 'c', 'd'] # 使用切片替换List中的部分元素 list2 = ['a', 'b', 'c', 'd'] list2[1:3] = ['e', 'f'] print(list2) # 输出 ['a', 'e', 'f', 'd']
2. 添加和删除元素
List中提供了多种方法来添加和删除元素。可以使用append()方法在List的末尾添加一个元素,使用insert()方法在指定位置插入一个元素,使用remove()方法删除指定元素,使用pop()方法删除List的指定位置的元素。
# 添加元素
list1 = ['a', 'b', 'c', 'd']
list1.append('e')
print(list1) # 输出 ['a', 'b', 'c', 'd', 'e']
# 插入元素
list2 = ['a', 'b', 'd', 'e']
list2.insert(2, 'c')
print(list2) # 输出 ['a', 'b', 'c', 'd', 'e']
# 删除元素
list3 = ['a', 'b', 'c', 'd']
list3.remove('c')
print(list3) # 输出 ['a', 'b', 'd']
# 删除指定位置的元素
list4 = ['a', 'b', 'c', 'd']
list4.pop(2)
print(list4) # 输出 ['a', 'b', 'd']
四、 List的高级操作
1. 列表的遍历
List可以使用for循环进行遍历。可以使用range()函数来生成需要遍历的索引值,也可以直接遍历List中的元素。
# 遍历List中的元素
list1 = ['a', 'b', 'c']
for i in list1:
print(i)
# 输出 a b c
# 遍历List中的索引值
list2 = ['a', 'b', 'c']
for i in range(len(list2)):
print(i, list2[i])
# 输出
# 0 a
# 1 b
# 2 c
2. 列表的排序、查询和计数
List提供了多种方法来对其进行排序,查询和计数。
# 按照元素首字母的ASCII码进行排序
list1 = ['c', 'a', 'b', 'd']
list1.sort()
print(list1) # 输出 ['a', 'b', 'c', 'd']
# 反向排序
list2 = ['c', 'a', 'b', 'd']
list2.sort(reverse=True)
print(list2) # 输出 ['d', 'c', 'b', 'a']
# 查询元素的索引值
list3 = ['a', 'b', 'c', 'c']
print(list3.index('c')) # 输出 2
# 计算元素在List中出现的次数
list4 = ['a', 'b', 'c', 'c']
print(list4.count('c')) # 输出 2
3. 列表的切片和连接
可以使用切片操作来获取List中的一段元素,也可以使用+运算符来连接两个List。
# 从List中获取一段元素 list1 = ['a', 'b', 'c', 'd', 'e'] print(list1[1:4]) # 输出 ['b', 'c', 'd'] # 连接两个List list2 = ['a', 'b', 'c'] list3 = ['d', 'e', 'f'] list4 = list2 + list3 print(list4) # 输出 ['a', 'b', 'c', 'd', 'e', 'f']
五、总结
Python中的List是一个灵活而强大的数据类型,可以用于存储任意类型的数据,并且提供了多种基本操作和高级操作。List的灵活性和强大性使得它成为Python中不可或缺的数据类型之一。在Python编程中,掌握List的使用和操作是至关重要的。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/257929.html
微信扫一扫
支付宝扫一扫