Skip to content

Python 列表 (List)

列表是 Python 中最基本、最常用的数据结构之一。它是一个有序可变的集合,可以包含任意类型的对象。

创建列表

列表由方括号 [] 定义,其中的元素用逗号 , 分隔。

python
# 创建一个空列表
empty_list = []

# 包含整数的列表
numbers = [1, 2, 3, 4, 5]

# 包含字符串的列表
fruits = ["apple", "banana", "cherry"]

# 包含混合数据类型的列表
mixed_list = [1, "hello", 3.14, True]

# 也可以使用 list() 构造函数
from_tuple = list((1, 2, 3)) # 从元组创建列表

访问列表元素

与字符串一样,你可以通过索引切片来访问列表中的元素。

索引 (Indexing)

python
fruits = ["apple", "banana", "cherry"]

print(fruits[0])   # 输出: 'apple'
print(fruits[1])   # 输出: 'banana'
print(fruits[-1])  # 输出: 'cherry' (最后一个元素)

切片 (Slicing)

python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 获取从索引 2 到 4 的元素
print(numbers[2:5])  # 输出: [2, 3, 4]

# 获取前 3 个元素
print(numbers[:3])   # 输出: [0, 1, 2]

# 获取从索引 5 到末尾的元素
print(numbers[5:])   # 输出: [5, 6, 7, 8, 9]

# 步长为 2 的切片
print(numbers[::2])  # 输出: [0, 2, 4, 6, 8]

列表是可变的 (Mutable)

与字符串和元组不同,列表是可变的。这意味着你可以修改、添加和删除列表中的元素。

python
fruits = ["apple", "banana", "cherry"]

# 修改元素
fruits[1] = "blueberry"
print(fruits)  # 输出: ['apple', 'blueberry', 'cherry']

常用列表方法

Python 为列表提供了丰富的内置方法。

  • list.append(x): 在列表末尾添加一个元素 x
  • list.insert(i, x): 在指定位置 i 插入一个元素 x
  • list.extend(iterable): 将一个可迭代对象(如另一个列表)的所有元素添加到列表末尾。
  • list.remove(x): 移除列表中第一个值为 x 的元素。
  • list.pop(i): 移除并返回指定位置 i 的元素。如果未指定索引,则移除并返回最后一个元素。
  • list.clear(): 清空列表中的所有元素。
  • list.index(x): 返回列表中第一个值为 x 的元素的索引。
  • list.count(x): 返回元素 x 在列表中出现的次数。
  • list.sort(): 对列表进行原地排序(会修改原列表)。
  • list.reverse(): 将列表中的元素原地反转。
  • list.copy(): 返回列表的浅拷贝。

示例:

python
my_list = [3, 1, 4]

# 添加元素
my_list.append(1)
print(my_list) # 输出: [3, 1, 4, 1]

# 插入元素
my_list.insert(2, 5) # 在索引2处插入5
print(my_list) # 输出: [3, 1, 5, 4, 1]

# 移除元素
my_list.remove(1) # 移除第一个1
print(my_list) # 输出: [3, 5, 4, 1]

# 弹出元素
popped_item = my_list.pop()
print(f"Popped: {popped_item}, List is now: {my_list}") # Popped: 1, List is now: [3, 5, 4]

# 排序
my_list.sort()
print(my_list) # 输出: [3, 4, 5]

列表操作

  • 连接: 使用 + 号可以连接两个列表,生成一个新列表。
  • 重复: 使用 * 号可以重复列表中的元素。
python
list1 = [1, 2]
list2 = [3, 4]

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

本站内容仅供学习和研究使用。