大家好,欢迎来到IT知识分享网。
艾瑞巴蒂干货来了,数据列表,骚话没有直接来吧
列表(List)是Python中最基本、最常用的数据结构之一,它是一个有序的可变集合,可以包含任意类型的元素。
列表的基本特性
- 有序集合:元素按插入顺序存储
- 可变性:创建后可以修改
- 异构性:可以包含不同类型的元素
- 可嵌套:列表中可以包含其他列表
- 可迭代:可以使用循环遍历
创建列表
# 空列表 empty_list = [] empty_list = list() # 包含元素的列表 numbers = [1, 2, 3, 4, 5] fruits = ['apple', 'banana', 'cherry'] mixed = [1, 'hello', 3.14, True]
列表操作示例
1. 访问元素
fruits = ['apple', 'banana', 'cherry', 'orange'] # 通过索引访问 print(fruits[0]) # 'apple' (正向索引从0开始) print(fruits[-1]) # 'orange' (负索引表示从末尾开始) # 切片操作 print(fruits[1:3]) # ['banana', 'cherry'] print(fruits[:2]) # ['apple', 'banana'] print(fruits[2:]) # ['cherry', 'orange'] print(fruits[::-1]) # 反转列表 ['orange', 'cherry', 'banana', 'apple']
2. 修改列表
# 修改元素 fruits[1] = 'blueberry' print(fruits) # ['apple', 'blueberry', 'cherry', 'orange'] # 添加元素 fruits.append('grape') # 末尾添加 fruits.insert(1, 'mango') # 在指定位置插入 # 合并列表 more_fruits = ['pear', 'kiwi'] fruits.extend(more_fruits) # 或 fruits += more_fruits
3. 删除元素
# 按值删除 fruits.remove('cherry') # 按索引删除 del fruits[0] popped = fruits.pop(2) # 删除并返回指定位置的元素 # 清空列表
4. 列表常用方法
numbers = [5, 2, 8, 1, 9] # 排序 numbers.sort() # 原地排序 [1, 2, 5, 8, 9] sorted_numbers = sorted(numbers, reverse=True) # 返回新列表 [9, 8, 5, 2, 1] # 反转 numbers.reverse() # 查找 index = numbers.index(5) # 返回第一个匹配项的索引 count = numbers.count(2) # 统计出现次数 # 复制 numbers_copy = numbers.copy() # 浅拷贝 numbers_deepcopy = numbers.deepcopy() # 深拷贝(需要import copy)
5. 列表推导式
# 创建平方数列表 squares = [x2 for x in range(10)] # 带条件的列表推导式 even_squares = [x2 for x in range(10) if x % 2 == 0] # 嵌套列表推导式 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row]
6. 嵌套列表
# 创建二维列表(矩阵) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # 访问嵌套列表元素 print(matrix[1][2]) # 6 # 遍历嵌套列表 for row in matrix: for num in row: print(num, end=' ') print()
7. 其他实用操作
# 列表长度 length = len(fruits) # 成员检查 if 'apple' in fruits: print("Apple is in the list") # 列表拼接 combined = fruits + numbers # 重复列表 repeated = [0] * 5 # [0, 0, 0, 0, 0] # 解包 first, second, *rest = [1, 2, 3, 4, 5]
- 在列表开头插入/删除元素(insert(0, x), pop(0))的时间复杂度是O(n)
- 在列表末尾插入/删除元素(append(x), pop())的时间复杂度是O(1)
- 随机访问元素的时间复杂度是O(1)
- 搜索元素的时间复杂度是O(n)
需要频繁在两端插入/删除元素时,应考虑使用collections.deque。
列表是Python编程中很重要的数据结构,掌握它的各种操作方法能显著提高编程效率和代码质量。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/176133.html