专业编程基础技术教程

网站首页 > 基础教程 正文

Python 列表(List)详解

ccvgpt 2025-04-27 12:40:44 基础教程 6 ℃

列表是 Python 中最基本、最常用的数据结构之一,它是一个有序的、可变的元素集合。

一、列表的基本操作

1. 创建列表

# 空列表
empty_list = []
empty_list = list()

# 包含元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed = [1, 'hello', 3.14, True]

# 使用list()构造函数
list_from_string = list('Python')  # ['P', 'y', 't', 'h', 'o', 'n']
list_from_range = list(range(5))   # [0, 1, 2, 3, 4]

2. 访问列表元素

fruits = ['apple', 'banana', 'orange', 'grape']

# 正索引访问(从0开始)
print(fruits[0])   # 'apple'
print(fruits[2])   # 'orange'

# 负索引访问(从-1开始)
print(fruits[-1])  # 'grape'
print(fruits[-3])  # 'banana'

# 切片操作 [start:end:step]
print(fruits[1:3])    # ['banana', 'orange']
print(fruits[:2])     # ['apple', 'banana']
print(fruits[::2])    # ['apple', 'orange'] (步长为2)
print(fruits[::-1])   # ['grape', 'orange', 'banana', 'apple'] (反转列表)

3. 修改列表

fruits = ['apple', 'banana', 'orange']

# 修改单个元素
fruits[1] = 'pear'
print(fruits)  # ['apple', 'pear', 'orange']

# 修改切片
fruits[1:3] = ['grape', 'kiwi']
print(fruits)  # ['apple', 'grape', 'kiwi']

# 添加单个元素
fruits.append('melon')
print(fruits)  # ['apple', 'grape', 'kiwi', 'melon']

# 添加多个元素
fruits.extend(['peach', 'berry'])
print(fruits)  # ['apple', 'grape', 'kiwi', 'melon', 'peach', 'berry']

二、列表常用方法

1. 添加元素
nums = [1, 2, 3]

# append() - 在末尾添加单个元素
nums.append(4)  # [1, 2, 3, 4]

# extend() - 添加多个元素(合并列表)
nums.extend([5, 6])  # [1, 2, 3, 4, 5, 6]

# insert() - 在指定位置插入元素
nums.insert(0, 0)  # [0, 1, 2, 3, 4, 5, 6]

2. 删除元素

nums = [0, 1, 2, 3, 4, 5, 6, 3]

# remove() - 删除第一个匹配的元素
nums.remove(3)  # [0, 1, 2, 4, 5, 6, 3]

# pop() - 删除并返回指定位置的元素(默认最后一个)
last = nums.pop()  # 返回3, nums变为[0, 1, 2, 4, 5, 6]
second = nums.pop(1)  # 返回1, nums变为[0, 2, 4, 5, 6]

# del语句 - 删除指定位置或切片
del nums[0]  # [2, 4, 5, 6]
del nums[1:3]  # [2, 6]

# clear() - 清空列表
nums.clear()  # []

3. 查找和统计

letters = ['a', 'b', 'c', 'a', 'd', 'a']

# index() - 返回元素的第一个匹配位置
print(letters.index('a'))  # 0
print(letters.index('a', 1))  # 3 (从位置1开始查找)

# count() - 统计元素出现次数
print(letters.count('a'))  # 3
print(letters.count('x'))  # 0

# in操作符 - 检查元素是否存在
print('b' in letters)  # True
print('x' in letters)  # False

4. 排序和反转

nums = [3, 1, 4, 1, 5, 9, 2]

# sort() - 原地排序
nums.sort()  # [1, 1, 2, 3, 4, 5, 9]
nums.sort(reverse=True)  # [9, 5, 4, 3, 2, 1, 1]

# sorted() - 返回新排序列表(不改变原列表)
sorted_nums = sorted(nums)  # [1, 1, 2, 3, 4, 5, 9]

# reverse() - 原地反转列表
nums.reverse()  # [9, 5, 4, 3, 2, 1, 1] -> [1, 1, 2, 3, 4, 5, 9]

三、列表的高级操作

1. 列表推导式

# 创建平方数列表
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

2. 列表复制

original = [1, 2, 3]

# 浅拷贝(三种方式)
copy1 = original.copy()
copy2 = list(original)
copy3 = original[:]

# 深拷贝(用于嵌套列表)
import copy
nested = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(nested)

3. 列表与字符串转换

# 字符串转列表
s = "hello"
char_list = list(s)  # ['h', 'e', 'l', 'l', 'o']

# 列表转字符串
words = ['Python', 'is', 'great']
sentence = ' '.join(words)  # "Python is great"

四、列表性能考虑

  1. 时间复杂度
  2. 索引访问:O(1)
  3. 末尾追加/删除:O(1)
  4. 中间插入/删除:O(n)
  5. 查找元素:O(n)
  6. 选择合适的数据结构
  7. 频繁在首部插入/删除:考虑 collections.deque
  8. 频繁查找/去重:考虑 set 或 dict
  9. 不可变序列:考虑 tuple

五、实际应用示例

# 示例1:处理成绩数据
grades = [85, 90, 78, 92, 88]

# 计算平均分
average = sum(grades) / len(grades)

# 找出高于平均分的成绩
above_avg = [g for g in grades if g > average]

# 示例2:矩阵转置
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(3)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

列表是 Python 中最灵活的数据结构之一,掌握它的各种操作和特性对于编写高效、清晰的 Python 代码至关重要。

Python 列表(List)详解

Tags:

最近发表
标签列表