数据结构是计算机存储、组织数据的方式。对于任何编程语言而言,理解其内置的数据结构都至关重要,Python 也不例外。Python 提供了丰富且易用的内置数据结构,它们不仅功能强大,而且语法简洁,极大地提升了开发效率。本文将带你深入了解 Python 中最核心的几种数据结构:列表 (List)、元组 (Tuple)、字典 (Dictionary) 和集合 (Set)。

列表 (List)

列表是 Python 中使用最频繁的数据结构之一。它是一个有序的、可变的元素序列,可以包含任意类型的对象。

特性:

  • 有序性:列表中的元素按照它们被添加的顺序存储,每个元素都有一个唯一的索引。
  • 可变性:列表创建后,可以随意添加、删除或修改其中的元素。
  • 异构性:列表中可以包含不同数据类型的元素,如整数、字符串、甚至其他列表。

创建列表:
可以使用方括号 []list() 构造函数来创建列表。

1
2
3
4
5
6
7
8
9
# 空列表
empty_list = []
another_empty_list = list()

# 包含元素的列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
nested_list = [[1, 2], ["a", "b"]]

常用操作:

  • 访问元素:通过索引(从0开始)或切片。

    1
    2
    3
    print(fruits[0])  # 输出: apple
    print(numbers[1:3]) # 输出: [2, 3] (不包括索引3的元素)
    print(mixed_list[-1]) # 输出: True (负索引表示从末尾开始)
  • 添加元素

    • append(element): 在列表末尾添加元素。
    • insert(index, element): 在指定索引位置插入元素。
    1
    2
    3
    4
    fruits.append("orange")
    print(fruits) # 输出: ['apple', 'banana', 'cherry', 'orange']
    fruits.insert(1, "grape")
    print(fruits) # 输出: ['apple', 'grape', 'banana', 'cherry', 'orange']
  • 删除元素

    • remove(element): 删除第一个匹配的元素。
    • pop(index=-1): 删除并返回指定索引的元素(默认为最后一个)。
    • del list_name[index]del list_name[start:end]: 删除指定索引或切片的元素。
    1
    2
    3
    4
    5
    6
    7
    fruits.remove("banana")
    print(fruits) # 输出: ['apple', 'grape', 'cherry', 'orange']
    popped_fruit = fruits.pop(0)
    print(popped_fruit) # 输出: apple
    print(fruits) # 输出: ['grape', 'cherry', 'orange']
    del numbers[0:2]
    print(numbers) # 输出: [3, 4, 5]
  • 修改元素

    1
    2
    fruits[0] = "mango"
    print(fruits) # 输出: ['mango', 'cherry', 'orange']
  • 其他常用方法

    • len(list): 返回列表长度。
    • list.sort(): 原地对列表进行排序。
    • sorted(list): 返回一个新的已排序列表,原列表不变。
    • list.reverse(): 原地反转列表。
    • element in list: 判断元素是否存在于列表中。
    • list.count(element): 返回元素在列表中出现的次数。
    • list.index(element): 返回元素首次出现的索引。

列表推导式 (List Comprehension):
一种简洁创建列表的方式。

1
2
3
4
5
squares = [x**2 for x in range(5)]
print(squares) # 输出: [0, 1, 4, 9, 16]

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # 输出: [0, 2, 4, 6, 8]

元组 (Tuple)

元组与列表类似,也是一个有序的元素序列。但元组是不可变的,一旦创建,其内容就不能被修改。

特性:

  • 有序性:与列表相同。
  • 不可变性:创建后不能修改、添加或删除元素。
  • 异构性:与列表相同。

创建元组:
使用圆括号 ()tuple() 构造函数。对于只包含一个元素的元组,需要在元素后面加上一个逗号。

1
2
3
4
5
6
7
8
# 空元组
empty_tuple = ()
another_empty_tuple = tuple()

# 包含元素的元组
colors = ("red", "green", "blue")
point = (10, 20)
single_element_tuple = (5,) # 注意逗号

与列表的主要区别:
最大的区别在于可变性。列表是可变的,元组是不可变的。

常用操作:
元组的操作与列表类似,但由于其不可变性,没有添加、删除、修改元素的方法。

  • 访问元素:通过索引或切片 (与列表相同)。
    1
    2
    print(colors[0])      # 输出: red
    print(point[0:1]) # 输出: (10,)
  • 其他常用方法
    • len(tuple): 返回元组长度。
    • element in tuple: 判断元素是否存在于元组中。
    • tuple.count(element): 返回元素在元组中出现的次数。
    • tuple.index(element): 返回元素首次出现的索引。

适用场景:

  • 当数据集合不应被修改时,如坐标点、配置参数等。
  • 作为字典的键(因为字典的键必须是不可变类型)。
  • 函数返回多个值时,实际上返回的是一个元组。

字典 (Dictionary)

字典是 Python 中另一种非常重要的数据结构,它存储键值对 (key-value pairs)。字典是无序的(在 Python 3.7+ 版本中,字典会记住插入顺序,表现为有序),可变的,并且键必须是唯一的、不可变类型(通常是字符串或数字,元组也可以)。

特性:

  • 键值对:每个元素都是一个 key: value 对。
  • 键唯一且不可变:字典中的键必须是唯一的。如果重复赋值,后面的会覆盖前面的。键必须是不可变类型。
  • 可变性:可以添加、删除或修改键值对。
  • 动态性:可以动态地增加或缩小。
  • 有序性(Python 3.7+):从 Python 3.7 开始,字典会保持元素的插入顺序。在之前的版本中,字典是无序的。

创建字典:
使用花括号 {}dict() 构造函数。

1
2
3
4
5
6
7
# 空字典
empty_dict = {}
another_empty_dict = dict()

# 包含元素的字典
person = {"name": "Alice", "age": 30, "city": "New York"}
scores = dict(math=90, english=85) # 使用 dict() 构造函数

常用操作:

  • 访问值:通过键来访问对应的值。

    1
    2
    3
    print(person["name"]) # 输出: Alice
    print(person.get("age")) # 输出: 30
    print(person.get("country", "Unknown")) # get() 方法可以指定默认值
  • 添加/修改键值对

    1
    2
    3
    4
    person["gender"] = "female" # 添加新的键值对
    person["age"] = 31 # 修改已存在的键值对
    print(person)
    # 输出: {'name': 'Alice', 'age': 31, 'city': 'New York', 'gender': 'female'}
  • 删除键值对

    • pop(key): 删除并返回指定键的值。
    • popitem(): 删除并返回字典中最后一对插入的键值对 (Python 3.7+) 或任意一对 (Python < 3.7)。
    • del dict_name[key]: 删除指定键的键值对。
    • clear(): 清空字典中所有键值对。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    city = person.pop("city")
    print(city) # 输出: New York
    print(person)
    # 输出: {'name': 'Alice', 'age': 31, 'gender': 'female'}

    last_item = person.popitem() # 假设 gender 是最后插入的
    print(last_item) # 输出: ('gender', 'female')

    del person["name"]
  • 获取视图对象

    • keys(): 返回一个包含所有键的视图对象。
    • values(): 返回一个包含所有值的视图对象。
    • items(): 返回一个包含所有 (键, 值) 元组的视图对象。
    1
    2
    3
    print(scores.keys())   # 输出: dict_keys(['math', 'english'])
    print(scores.values()) # 输出: dict_values([90, 85])
    print(scores.items()) # 输出: dict_items([('math', 90), ('english', 85)])
  • 遍历字典

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 遍历键
    for key in person:
    print(key, person[key])

    # 遍历值
    for value in person.values():
    print(value)

    # 遍历键值对
    for key, value in person.items():
    print(f"{key}: {value}")

字典推导式 (Dictionary Comprehension):

1
2
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

集合 (Set)

集合是一个无序的、不重复的元素序列。它主要用于成员测试和消除重复项。

特性:

  • 无序性:集合中的元素没有特定的顺序。
  • 唯一性:集合中不允许出现重复的元素。
  • 可变性:可以添加或删除元素 (但集合本身是可变的,其元素必须是不可变类型)。

创建集合:
使用花括号 {} (但不能创建空集合,{} 创建的是空字典) 或 set() 构造函数。

1
2
3
4
5
6
7
8
9
# 空集合
empty_set = set()

# 包含元素的集合
unique_numbers = {1, 2, 3, 2, 1} # 重复元素会被自动移除
print(unique_numbers) # 输出: {1, 2, 3} (顺序可能不同)

chars = set("hello")
print(chars) # 输出: {'e', 'h', 'l', 'o'} (顺序可能不同)

常用操作:

  • 添加元素

    • add(element): 添加单个元素。
    • update(iterable): 添加多个元素(来自可迭代对象)。
    1
    2
    3
    4
    unique_numbers.add(4)
    print(unique_numbers) # 输出: {1, 2, 3, 4}
    unique_numbers.update([3, 4, 5, 6])
    print(unique_numbers) # 输出: {1, 2, 3, 4, 5, 6}
  • 删除元素

    • remove(element): 删除指定元素,如果元素不存在则抛出 KeyError。
    • discard(element): 删除指定元素,如果元素不存在则什么也不做。
    • pop(): 随机删除并返回一个元素,如果集合为空则抛出 KeyError。
    • clear(): 清空集合。
    1
    2
    3
    4
    5
    unique_numbers.remove(1)
    # unique_numbers.remove(10) # 这会引发 KeyError
    unique_numbers.discard(2)
    unique_numbers.discard(10) # 不会报错
    print(unique_numbers.pop()) # 随机弹出一个元素
  • 集合运算

    • 并集 (Union): s1 | s2s1.union(s2) - 返回包含两个集合所有元素的新集合。
    • 交集 (Intersection): s1 & s2s1.intersection(s2) - 返回两个集合共有的元素组成的新集合。
    • 差集 (Difference): s1 - s2s1.difference(s2) - 返回在 s1 中但不在 s2 中的元素组成的新集合。
    • 对称差集 (Symmetric Difference): s1 ^ s2s1.symmetric_difference(s2) - 返回只在其中一个集合中出现的元素(即两个集合的并集减去交集)。
    1
    2
    3
    4
    5
    6
    7
    a = {1, 2, 3, 4}
    b = {3, 4, 5, 6}
    print(a.union(b)) # 输出: {1, 2, 3, 4, 5, 6}
    print(a.intersection(b)) # 输出: {3, 4}
    print(a.difference(b)) # 输出: {1, 2}
    print(b.difference(a)) # 输出: {5, 6}
    print(a.symmetric_difference(b)) # 输出: {1, 2, 5, 6}
  • 其他常用方法

    • len(set): 返回集合中元素的数量。
    • element in set: 判断元素是否存在于集合中(效率很高)。
    • s1.issubset(s2): 判断 s1 是否是 s2 的子集。
    • s1.issuperset(s2): 判断 s1 是否是 s2 的超集。
    • s1.isdisjoint(s2): 判断两个集合是否没有交集。

主要用途:

  • 去除序列中的重复元素。
  • 成员资格测试。
  • 进行数学上的集合运算。

总结

Python 的内置数据结构——列表、元组、字典和集合——为我们提供了强大而灵活的工具来处理和组织数据。

  • 当你需要一个有序且可变的序列时,选择列表
  • 当你需要一个有序但不可变的序列时,选择元组
  • 当你需要存储键值对,并通过键快速查找值时,选择字典
  • 当你需要一个不重复元素的集合,并进行成员测试或集合运算时,选择集合

熟练掌握这些数据结构的特性和用法,将使你的 Python 编程之旅更加顺畅和高效。希望本文能帮助你更好地理解和运用它们!