DukeDuke
主页
文档转换
关于我们
主页
文档转换
关于我们
  • 什么是Python
  • Python简介
  • Python安装
  • Python基础语法
  • Python数据类型
  • Python数字
  • Python字符串
  • Python列表
  • Python元组
  • Python字典
  • Python日期时间
  • Python文件操作
  • Python异常处理
  • Python函数
  • Python类
  • Python模块
  • Python包
  • Python多线程
  • Python面向对象
  • Python爬虫
  • Django web框架

Python 列表(List)

列表是 Python 中最常用的数据类型之一,它是一个有序的、可变的集合。列表可以包含不同类型的元素,包括数字、字符串、甚至其他列表。

1. 创建列表

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

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

2. 访问列表元素

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

# 使用索引访问元素(索引从0开始)
first_fruit = fruits[0]    # 'apple'
second_fruit = fruits[1]   # 'banana'

# 使用负数索引从末尾访问
last_fruit = fruits[-1]    # 'orange'

# 切片操作
first_two = fruits[0:2]    # ['apple', 'banana']

3. 修改列表

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

# 修改元素
fruits[1] = 'grape'        # ['apple', 'grape', 'orange']

# 添加元素
fruits.append('mango')     # ['apple', 'grape', 'orange', 'mango']
fruits.insert(1, 'pear')   # ['apple', 'pear', 'grape', 'orange', 'mango']

# 删除元素
fruits.remove('grape')     # ['apple', 'pear', 'orange', 'mango']
popped_fruit = fruits.pop() # 删除并返回最后一个元素
del fruits[0]              # 删除指定索引的元素

4. 列表操作

# 列表连接
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2   # [1, 2, 3, 4, 5, 6]

# 列表重复
repeated = list1 * 2       # [1, 2, 3, 1, 2, 3]

# 列表长度
length = len(list1)        # 3

# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()             # [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1]

# 列表反转
numbers.reverse()          # [1, 1, 2, 3, 4, 5, 6, 9]

5. 列表推导式

列表推导式提供了一种简洁的方式来创建列表:

# 创建1到10的平方数列表
squares = [x**2 for x in range(1, 11)]

# 创建偶数列表
evens = [x for x in range(1, 11) if x % 2 == 0]

# 创建字符串列表
words = ['hello', 'world', 'python']
upper_words = [word.upper() for word in words]

6. 常用列表方法

numbers = [1, 2, 3, 4, 5]

# 添加元素
numbers.append(6)          # 在末尾添加元素
numbers.extend([7, 8])     # 扩展列表
numbers.insert(0, 0)       # 在指定位置插入元素

# 删除元素
numbers.remove(3)          # 删除指定值的元素
numbers.pop()              # 删除并返回最后一个元素
numbers.clear()            # 清空列表

# 查找元素
index = numbers.index(4)   # 返回元素的索引
count = numbers.count(2)   # 返回元素出现的次数

7. 列表的注意事项

  1. 列表是可变的,可以随时修改其内容
  2. 列表可以包含不同类型的元素
  3. 列表的索引从 0 开始
  4. 使用切片时,返回的是一个新的列表
  5. 列表操作可能会影响性能,特别是在处理大型列表时

8. 实际应用示例

# 学生成绩管理
scores = [85, 92, 78, 90, 88]

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

# 找出最高分和最低分
highest = max(scores)
lowest = min(scores)

# 成绩排序
sorted_scores = sorted(scores, reverse=True)

# 筛选及格分数
passing_scores = [score for score in scores if score >= 60]

9. 性能考虑

  1. 在列表开头插入或删除元素的时间复杂度是 O(n)
  2. 在列表末尾添加或删除元素的时间复杂度是 O(1)
  3. 访问元素的时间复杂度是 O(1)
  4. 搜索元素的时间复杂度是 O(n)

对于需要频繁在开头插入或删除元素的场景,建议使用 collections.deque。

最近更新:: 2026/4/17 13:21
Contributors: Duke
Prev
Python字符串
Next
Python元组