python3 列表详解

在 Python3 中,列表(List)是一种灵活且功能强大的数据结构,用于有序存储多个元素。它是 Python 最常用的数据类型之一,支持动态调整大小、嵌套结构以及丰富的操作方法。以下是 Python3 列表的详细介绍:

一、列表基础

1. 定义列表

使用方括号[]定义,元素之间用逗号分隔:
 
 
empty_list = []                  # 空列表
numbers = [1, 2, 3, 4, 5]        # 数字列表
fruits = ['apple', 'banana', 'cherry']  # 字符串列表
mixed = [1, 'apple', True, 3.14]  # 混合类型列表
nested = [[1, 2], [3, 4], [5]]   # 嵌套列表
 

2. 列表特点

  • 有序性:元素按插入顺序排列,可通过索引访问。
  • 可变性:列表元素可修改、添加或删除。
  • 异构性:允许存储不同类型的元素。
  • 可嵌套:列表中可包含其他列表或数据结构。

二、列表操作

1. 索引与切片

fruits = ['apple', 'banana', 'cherry', 'date']

# 正向索引
print(fruits[0])    # 输出: apple
print(fruits[2])    # 输出: cherry

# 负向索引
print(fruits[-1])   # 输出: date
print(fruits[-3])   # 输出: banana

# 切片 [start:stop:step]
print(fruits[1:3])  # 输出: ['banana', 'cherry']
print(fruits[:2])   # 输出: ['apple', 'banana']
print(fruits[2:])   # 输出: ['cherry', 'date']
print(fruits[::2])  # 输出: ['apple', 'cherry']
print(fruits[::-1]) # 反转列表: ['date', 'cherry', 'banana', 'apple']
 

2. 列表修改

numbers = [1, 2, 3, 4]

# 修改元素
numbers[1] = 20
print(numbers)  # 输出: [1, 20, 3, 4]

# 切片赋值
numbers[1:3] = [200, 300]
print(numbers)  # 输出: [1, 200, 300, 4]
 

三、列表方法

1. 添加元素

fruits = ['apple', 'banana']

# append():在末尾添加单个元素
fruits.append('cherry')
print(fruits)  # 输出: ['apple', 'banana', 'cherry']

# extend():在末尾添加多个元素
fruits.extend(['date', 'elderberry'])
print(fruits)  # 输出: ['apple', 'banana', 'cherry', 'date', 'elderberry']

# insert():在指定位置插入元素
fruits.insert(1, 'avocado')
print(fruits)  # 输出: ['apple', 'avocado', 'banana', 'cherry', 'date', 'elderberry']
 

2. 删除元素

fruits = ['apple', 'banana', 'cherry', 'date']

# remove():按值删除
fruits.remove('banana')
print(fruits)  # 输出: ['apple', 'cherry', 'date']

# pop():按索引删除并返回元素
popped = fruits.pop(1)
print(popped)  # 输出: cherry
print(fruits)  # 输出: ['apple', 'date']

# clear():清空列表
fruits.clear()
print(fruits)  # 输出: []
 

3. 查找与统计

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

# index():查找元素首次出现的索引
print(fruits.index('apple'))  # 输出: 0

# count():统计元素出现次数
print(fruits.count('apple'))  # 输出: 2
 

4. 排序与反转

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

# sort():原地排序
numbers.sort()
print(numbers)  # 输出: [1, 1, 3, 4, 5, 9]

# sort() 逆序
numbers.sort(reverse=True)
print(numbers)  # 输出: [9, 5, 4, 3, 1, 1]

# sorted():返回新的排序列表
new_numbers = sorted(numbers)
print(new_numbers)  # 输出: [1, 1, 3, 4, 5, 9]

# reverse():反转列表
numbers.reverse()
print(numbers)  # 输出: [9, 5, 4, 3, 1, 1]
 

四、列表运算

1. 拼接与重复

 
list1 = [1, 2]
list2 = [3, 4]

# 拼接
print(list1 + list2)  # 输出: [1, 2, 3, 4]

# 重复
print(list1 * 3)      # 输出: [1, 2, 1, 2, 1, 2]
 

2. 成员测试

fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits)    # 输出: True
print('date' not in fruits) # 输出: True
 

3. 长度与比较

numbers = [1, 2, 3]
print(len(numbers))  # 输出: 3

# 比较(按元素逐个比较)
print([1, 2] < [1, 3])  # 输出: True
 

五、列表推导式

高效创建列表的语法:

# 生成平方数列表
squares = [x**2 for x in range(5)]
print(squares)  # 输出: [0, 1, 4, 9, 16]

# 带条件的列表推导式
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # 输出: [0, 2, 4, 6, 8]

# 嵌套列表推导式
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)  # 输出: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
 

六、高级技巧

1. 解包(Unpacking)

numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c)  # 输出: 1 2 3

# 部分解包
first, *rest = [1, 2, 3, 4]
print(first)    # 输出: 1
print(rest)     # 输出: [2, 3, 4]
 

2. 遍历技巧

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

# 带索引遍历
for index, fruit in enumerate(fruits):
    print(index, fruit)
# 输出:
# 0 apple
# 1 banana
# 2 cherry

# 同时遍历多个列表
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f'{name} is {age} years old.')
 

3. 复制列表

# 浅复制(只复制外层结构)
original = [1, [2, 3]]
shallow_copy = original.copy()  # 或 list(original) 或 original[:]
shallow_copy[1][0] = 200
print(original)  # 输出: [1, [200, 3]]

# 深复制(递归复制所有嵌套结构)
import copy
original = [1, [2, 3]]
deep_copy = copy.deepcopy(original)
deep_copy[1][0] = 200
print(original)  # 输出: [1, [2, 3]]
 

七、性能考虑

  1. 列表操作性能
    • append()pop()在尾部操作效率高(O (1))。
    • insert()remove()在中间操作效率低(O (n))。
    • 列表切片会创建新列表,大数据量时需注意内存占用。
  2. 替代数据结构
    • 若需频繁在头部插入 / 删除,考虑使用collections.deque
    • 若需高效查找,考虑使用集合(Set)或字典(Dictionary)。

八、总结

  • 核心特性:有序、可变、异构、可嵌套。
  • 常用操作:索引、切片、修改、添加、删除、排序等。
  • 高效工具:列表推导式、解包、遍历技巧。
  • 注意事项:浅复制与深复制的区别,操作性能瓶颈。

列表是 Python 中最灵活的数据结构之一,掌握其用法对编写高效、简洁的代码至关重要。通过合理运用列表的各种特性,可以轻松处理各种数据处理和算法问题。

posted on 2025-06-20 10:52  小陶coding  阅读(91)  评论(0)    收藏  举报