人工智能之编程基础 Python 入门:第六章 基本数据类型(二)

人工智能之编程基础 Python 入门

第六章 基础数据类型(二)


@
目录

  • [人工智能之编程基础 Python 入门](#人工智能之编程基础 Python 入门)
  • 前言
  • List(列表)
    • [1. 列表的创建](#1. 列表的创建)
    • [2. 列表的特性](#2. 列表的特性)
    • [3. 列表的访问](#3. 列表的访问)
    • [4. 列表的修改(可变性)](#4. 列表的修改(可变性))
    • [5. 常用列表方法](#5. 常用列表方法)
    • [6. 列表操作](#6. 列表操作)
    • [7. 列表推导式(List Comprehension)](#7. 列表推导式(List Comprehension))
    • [8. 遍历列表](#8. 遍历列表)
    • [9. 嵌套列表](#9. 嵌套列表)
    • [10. 注意事项与陷阱](#10. 注意事项与陷阱)
      • [1. 可变对象的引用](#1. 可变对象的引用)
      • [2. 修改列表时的索引问题](#2. 修改列表时的索引问题)
    • [11. 列表 vs 元组](#11. 列表 vs 元组)
  • Dictionary(字典)
    • [1. 字典的创建](#1. 字典的创建)
    • [2. 字典的特性](#2. 字典的特性)
    • [3. 字典的基本操作](#3. 字典的基本操作)
    • [4. 字典的常用方法](#4. 字典的常用方法)
    • [5. 遍历字典](#5. 遍历字典)
    • [6. 字典推导式](#6. 字典推导式)
    • [7. 嵌套字典](#7. 嵌套字典)
    • [8. 实用技巧和最佳实践](#8. 实用技巧和最佳实践)
      • [1. 使用 get() 防止 KeyError](#1. 使用 get() 防止 KeyError)
      • [2. 设置默认值](#2. 设置默认值)
      • [3. 合并字典(Python 3.9+)](#3. 合并字典(Python 3.9+))
    • [9. 注意事项](#9. 注意事项)
      • [1. 可哈希的键](#1. 可哈希的键)
      • [2. 浅拷贝问题](#2. 浅拷贝问题)
    • [10. 字典的应用场景](#10. 字典的应用场景)
  • Set(集合)
    • [1. 集合的创建](#1. 集合的创建)
    • [2. 集合的特性](#2. 集合的特性)
    • [3. 集合的基本操作](#3. 集合的基本操作)
    • [4. 集合的数学运算](#4. 集合的数学运算)
    • [5. 集合推导式](#5. 集合推导式)
    • [6. 不可变集合:frozenset](#6. 不可变集合:frozenset)
    • [7. 遍历集合](#7. 遍历集合)
    • [8. 实际应用示例](#8. 实际应用示例)
      • [1. 去除重复元素](#1. 去除重复元素)
      • [2. 成员资格测试(高效)](#2. 成员资格测试(高效))
      • [3. 文本处理](#3. 文本处理)
      • [4. 比较数据集](#4. 比较数据集)
    • [9. 注意事项](#9. 注意事项)
      • [1. 可变元素不能放入集合](#1. 可变元素不能放入集合)
      • [2. 集合本身不可哈希](#2. 集合本身不可哈希)
      • [3. 空集合的创建](#3. 空集合的创建)
    • [10. 性能特点](#10. 性能特点)
  • 总结
  • 资料关注

前言

本章节紧接上一章的内容学习python的可变数据类型List(列表)、Dictionary(字典)、Set(集合)。


List(列表)

在 Python 中,列表(List) 是一种有序、可变的序列数据类型。它是 Python 最常用和最灵活的数据结构之一,可以存储任意类型的对象(整数、字符串、其他列表等),并且允许重复元素。


1. 列表的创建

python 复制代码
# 使用方括号 []
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True, [1, 2]]

# 使用 list() 构造函数
list_from_string = list("hello")        # ['h', 'e', 'l', 'l', 'o']
list_from_range = list(range(5))        # [0, 1, 2, 3, 4]

2. 列表的特性

特性 说明
有序(Ordered) 元素有固定的顺序,可以通过索引访问
可变(Mutable) 可以添加、删除、修改元素
可重复(Allow Duplicates) 可以包含重复的元素
动态大小(Dynamic Size) 大小可以随时改变

3. 列表的访问

索引(Indexing)

python 复制代码
fruits = ["apple", "banana", "cherry"]

print(fruits[0])    # apple (第一个)
print(fruits[-1])   # cherry (最后一个)
# print(fruits[10])  # IndexError: list index out of range

切片(Slicing)

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

print(numbers[2:5])     # [2, 3, 4] (索引2到4)
print(numbers[:3])      # [0, 1, 2] (开头到索引2)
print(numbers[5:])      # [5, 6, 7, 8, 9] (索引5到末尾)
print(numbers[::2])     # [0, 2, 4, 6, 8] (每隔一个)
print(numbers[::-1])    # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (反转)

4. 列表的修改(可变性)

修改元素

python 复制代码
fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'cherry']

添加元素

python 复制代码
# append() - 在末尾添加单个元素
fruits.append("grape")

# insert() - 在指定位置插入元素
fruits.insert(1, "kiwi")  # 在索引1处插入

# extend() - 添加多个元素(另一个可迭代对象)
fruits.extend(["mango", "pineapple"])

删除元素

python 复制代码
# remove() - 删除第一个匹配的值
fruits.remove("apple")

# pop() - 删除并返回指定索引的元素(默认最后一个)
last_fruit = fruits.pop()
second_fruit = fruits.pop(1)

# del - 删除指定索引或切片
del fruits[0]
del fruits[1:3]  # 删除索引1到2的元素

# clear() - 清空列表
# fruits.clear()

5. 常用列表方法

python 复制代码
numbers = [3, 1, 4, 1, 5, 9, 2]

# 排序
numbers.sort()           # 升序排序(原地修改)
numbers.sort(reverse=True)  # 降序
sorted_numbers = sorted(numbers)  # 返回新列表,不修改原列表

# 反转
numbers.reverse()        # 原地反转
reversed_numbers = list(reversed(numbers))  # 返回迭代器

# 查找
print(numbers.index(4))  # 返回第一个匹配项的索引
print(numbers.count(1))  # 统计元素出现次数

# 复制(重要!)
original = [1, 2, 3]
shallow_copy = original.copy()  # 浅拷贝
# 或者使用切片: copy = original[:]

6. 列表操作

拼接

python 复制代码
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2  # [1, 2, 3, 4]

重复

python 复制代码
repeated = [1, 2] * 3  # [1, 2, 1, 2, 1, 2]

成员检查

python 复制代码
if "apple" in fruits:
    print("找到了苹果!")

长度

python 复制代码
length = len(fruits)

7. 列表推导式(List Comprehension)

一种简洁创建列表的方式。

python 复制代码
# 创建平方数列表
squares = [x**2 for x in range(10)]
# 等价于:
# squares = []
# for x in range(10):
#     squares.append(x**2)

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

# 字符串处理
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]

8. 遍历列表

python 复制代码
# 方法1:直接遍历元素
for fruit in fruits:
    print(fruit)

# 方法2:使用索引
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

# 方法3:使用 enumerate()(推荐)
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

9. 嵌套列表

列表可以包含其他列表,常用于表示二维数据(如矩阵)。

python 复制代码
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0][1])  # 2 (第一行第二列)

# 遍历二维列表
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

10. 注意事项与陷阱

1. 可变对象的引用

python 复制代码
# ❌ 错误:共享同一个列表对象
list_of_lists = [[]] * 3
list_of_lists[0].append(1)
print(list_of_lists)  # [[1], [1], [1]] 所有子列表都被修改!

# ✅ 正确:创建独立的列表
list_of_lists = [[] for _ in range(3)]
list_of_lists[0].append(1)
print(list_of_lists)  # [[1], [], []]

2. 修改列表时的索引问题

python 复制代码
# ❌ 在遍历中删除元素可能导致跳过元素
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # 危险!可能出错

# ✅ 正确的做法
# 方法1:反向遍历
for i in range(len(numbers) - 1, -1, -1):
    if numbers[i] % 2 == 0:
        del numbers[i]

# 方法2:创建新列表
numbers = [num for num in numbers if num % 2 != 0]

11. 列表 vs 元组

特性 列表 (List) 元组 (Tuple)
语法 [] ()
可变性 ✅ 可变 ❌ 不可变
性能 稍慢 更快
内存 占用更多 更节省
用途 存储可变集合 存储固定数据结构

Dictionary(字典)

在 Python 中,字典(Dictionary) 是一种非常强大且常用的数据结构,用于存储​键值对(key-value pairs) ​。它也被称为关联数组 或​哈希表​。


1. 字典的创建

python 复制代码
# 使用花括号 {}
empty_dict = {}
person = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

# 使用 dict() 构造函数
dict_from_pairs = dict([("a", 1), ("b", 2)])
dict_with_args = dict(name="Bob", age=30)

# 从其他数据结构创建
keys = ["x", "y", "z"]
values = [1, 2, 3]
coordinates = dict(zip(keys, values))  # {'x': 1, 'y': 2, 'z': 3}

2. 字典的特性

特性 说明
无序性 Python 3.7+ 保证插入顺序
可变性 可以添加、修改、删除键值对
键的唯一性 键必须唯一,重复的键会被覆盖
键的不可变性 键必须是可哈希的类型(如字符串、数字、元组)
值的任意性 值可以是任何类型,包括其他字典

3. 字典的基本操作

访问值

python 复制代码
person = {"name": "Alice", "age": 25}

# 使用方括号 []
print(person["name"])  # Alice

# 使用 get() 方法(推荐,更安全)
print(person.get("age"))     # 25
print(person.get("gender"))  # None (默认)
print(person.get("gender", "未知"))  # "未知" (指定默认值)

添加/修改元素

python 复制代码
# 添加新键值对
person["city"] = "Shanghai"

# 修改现有值
person["age"] = 26

# 使用 update() 批量更新
person.update({"job": "Engineer", "salary": 10000})

删除元素

python 复制代码
# pop() - 删除并返回指定键的值
age = person.pop("age")

# popitem() - 删除并返回最后一个键值对 (Python 3.7+)
last_item = person.popitem()

# del - 删除指定键
del person["city"]

# clear() - 清空字典
# person.clear()

4. 字典的常用方法

python 复制代码
person = {"name": "Alice", "age": 25, "city": "Beijing"}

# 获取所有键、值、键值对
print(person.keys())    # dict_keys(['name', 'age', 'city'])
print(person.values())  # dict_values(['Alice', 25, 'Beijing'])
print(person.items())   # dict_items([('name', 'Alice'), ('age', 25), ('city', 'Beijing')])

# 检查键是否存在
if "name" in person:
    print("存在 name 键")

# 获取字典长度
print(len(person))  # 3

# 复制字典
shallow_copy = person.copy()

5. 遍历字典

python 复制代码
person = {"name": "Alice", "age": 25, "city": "Beijing"}

# 遍历键
for key in person:
    print(key)

# 或者
for key in person.keys():
    print(key)

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

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

6. 字典推导式

类似于列表推导式,可以简洁地创建字典。

python 复制代码
# 创建平方数字典
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 带条件的字典推导式
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

# 转换现有字典
original = {"a": 1, "b": 2, "c": 3}
doubled = {k: v*2 for k, v in original.items()}
# {'a': 2, 'b': 4, 'c': 6}

7. 嵌套字典

字典的值可以是另一个字典,用于表示复杂的数据结构。

python 复制代码
students = {
    "Alice": {
        "age": 20,
        "grade": "A",
        "courses": ["Math", "Physics"]
    },
    "Bob": {
        "age": 21,
        "grade": "B",
        "courses": ["Chemistry", "Biology"]
    }
}

# 访问嵌套值
print(students["Alice"]["age"])           # 20
print(students["Bob"]["courses"][0])      # Chemistry

# 遍历嵌套字典
for name, info in students.items():
    print(f"{name}: {info['age']}岁, 成绩{info['grade']}")

8. 实用技巧和最佳实践

1. 使用 get() 防止 KeyError

python 复制代码
# ❌ 可能出错
# value = my_dict["missing_key"]

# ✅ 安全的做法
value = my_dict.get("missing_key", "默认值")

2. 设置默认值

python 复制代码
# setdefault() - 如果键不存在,则设置默认值
person.setdefault("gender", "未知")
# 如果"gender"键不存在,则添加并赋值"未知"

# defaultdict - 更高级的默认字典
from collections import defaultdict
word_count = defaultdict(int)  # 默认值为0
word_count["apple"] += 1  # 即使键不存在也不会报错

3. 合并字典(Python 3.9+)

python 复制代码
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

# 方法1:使用 | 操作符
merged = dict1 | dict2

# 方法2:使用 |= 更新
dict1 |= dict2

# 方法3:解包(适用于所有版本)
merged = {**dict1, **dict2}

9. 注意事项

1. 可哈希的键

python 复制代码
# ✅ 有效的键
valid_dict = {
    "string": 1,
    42: 2,
    (1, 2): 3,  # 元组可以作为键
    None: 4
}

# ❌ 无效的键(可变类型)
# invalid_dict = {[1, 2]: "value"}  # TypeError: unhashable type: 'list'
# invalid_dict = {{'a': 1}: "value"}  # TypeError: unhashable type: 'dict'

2. 浅拷贝问题

python 复制代码
original = {"a": [1, 2, 3]}
copy = original.copy()
copy["a"].append(4)
print(original)  # {'a': [1, 2, 3, 4]}! 原字典也被修改了

10. 字典的应用场景

  1. 配置管理
python 复制代码
config = {
    "host": "localhost",
    "port": 8080,
    "debug": True
}
  1. 缓存
python 复制代码
cache = {}
def get_data(key):
    if key in cache:
        return cache[key]
    # 计算数据...
    cache[key] = result
    return result
  1. 计数器
python 复制代码
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
  1. JSON 数据处理
python 复制代码
import json
data = json.loads('{"name": "Alice", "age": 25}')

Set(集合)

在 Python 中,集合(Set) 是一种无序、可变的容器数据类型,用于存储唯一的元素(即不包含重复项)。集合基于数学中的集合论,支持交集、并集、差集等操作。


1. 集合的创建

python 复制代码
# 使用花括号 {} - 注意:空集合不能用 {}
empty_set = set()  # ✅ 正确
# empty_set = {}   # ❌ 错误!这是空字典

# 非空集合可以用花括号
fruits = {"apple", "banana", "orange"}

# 使用 set() 构造函数
numbers = set([1, 2, 3, 2, 1])  # {1, 2, 3} 自动去重
chars = set("hello")             # {'h', 'e', 'l', 'o'} 注意 'l' 只出现一次

2. 集合的特性

特性 说明
无序性 元素没有固定顺序,不能通过索引访问
唯一性 自动去除重复元素
可变性 可以添加和删除元素(但有不可变集合 frozenset
可哈希性 集合本身不可哈希,不能作为字典的键或集合的元素
元素要求 集合中的元素必须是可哈希的(不可变类型)

3. 集合的基本操作

添加元素

python 复制代码
fruits = {"apple", "banana"}

# add() - 添加单个元素
fruits.add("orange")

# update() - 添加多个元素(任何可迭代对象)
fruits.update(["grape", "kiwi"])
fruits.update("xyz")  # 添加 'x', 'y', 'z'

删除元素

python 复制代码
# remove() - 删除指定元素,元素不存在时会报错
fruits.remove("banana")

# discard() - 删除指定元素,元素不存在时不会报错(推荐)
fruits.discard("mango")  # 即使没有也不会报错

# pop() - 随机删除并返回一个元素(因为无序)
random_fruit = fruits.pop()

# clear() - 清空集合
# fruits.clear()

检查成员

python 复制代码
if "apple" in fruits:
    print("苹果在集合中")

if "mango" not in fruits:
    print("没有芒果")

获取大小

python 复制代码
size = len(fruits)

4. 集合的数学运算

集合支持丰富的集合运算:

python 复制代码
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 并集 (Union) - 所有元素
print(set1 | set2)           # {1, 2, 3, 4, 5, 6}
print(set1.union(set2))

# 交集 (Intersection) - 共同元素
print(set1 & set2)           # {3, 4}
print(set1.intersection(set2))

# 差集 (Difference) - set1 有但 set2 没有的元素
print(set1 - set2)           # {1, 2}
print(set1.difference(set2))

# 对称差集 (Symmetric Difference) - 只在一个集合中的元素
print(set1 ^ set2)           # {1, 2, 5, 6}
print(set1.symmetric_difference(set2))

# 子集和超集
set3 = {1, 2}
print(set3 <= set1)          # True (set3 是 set1 的子集)
print(set1 >= set3)          # True (set1 是 set3 的超集)

5. 集合推导式

类似于列表推导式,可以简洁地创建集合。

python 复制代码
# 创建平方数集合
squares = {x**2 for x in range(5)}
# {0, 1, 4, 9, 16}

# 带条件的集合推导式
evens = {x for x in range(10) if x % 2 == 0}
# {0, 2, 4, 6, 8}

# 从字符串创建去重字符集
unique_chars = {c for c in "hello world" if c != " "}
# {'h', 'e', 'l', 'o', 'w', 'r', 'd'}

6. 不可变集合:frozenset

frozenset 是集合的不可变版本,创建后不能修改,因此它是可哈希的,可以用作字典的键或集合的元素。

python 复制代码
# 创建 frozenset
frozen = frozenset([1, 2, 3, 2])
print(frozen)  # frozenset({1, 2, 3})

# frozenset 支持所有集合运算,但不能修改
# frozen.add(4)  # ❌ AttributeError

# 用作字典的键
dict_with_frozen = {
    frozenset([1, 2]): "group1",
    frozenset([3, 4]): "group2"
}

7. 遍历集合

由于集合无序,遍历顺序不固定。

python 复制代码
fruits = {"apple", "banana", "orange"}

for fruit in fruits:
    print(fruit)

# 如果需要排序输出
for fruit in sorted(fruits):
    print(fruit)

8. 实际应用示例

1. 去除重复元素

python 复制代码
# 最常用的用途
original_list = [1, 2, 2, 3, 3, 3, 4]
unique_list = list(set(original_list))
print(unique_list)  # [1, 2, 3, 4] (顺序可能不同)

2. 成员资格测试(高效)

python 复制代码
# 集合的查找时间复杂度为 O(1),比列表 O(n) 快得多
valid_users = {"alice", "bob", "charlie"}

def check_access(username):
    return username in valid_users  # 非常快

3. 文本处理

python 复制代码
text = "hello world python"
vowels = set("aeiou")
text_chars = set(text)

# 找出文本中包含的元音字母
found_vowels = text_chars & vowels
print(found_vowels)  # {'o', 'e'}

4. 比较数据集

python 复制代码
current_users = {"alice", "bob", "david"}
previous_users = {"alice", "charlie", "bob"}

# 新增用户
new_users = current_users - previous_users  # {'david'}

# 离开用户
left_users = previous_users - current_users  # {'charlie'}

# 活跃用户(都有的)
active_users = current_users & previous_users  # {'alice', 'bob'}

9. 注意事项

1. 可变元素不能放入集合

python 复制代码
# ❌ 错误:列表是可变的,不可哈希
# invalid_set = {[1, 2], [3, 4]}  # TypeError

# ✅ 正确:使用元组(不可变)
valid_set = {(1, 2), (3, 4)}

2. 集合本身不可哈希

python 复制代码
# ❌ 错误
# dict_with_set = {{"a", "b"}: "value"}  # TypeError

# ✅ 正确:使用 frozenset
dict_with_frozen = {frozenset(["a", "b"]): "value"}

3. 空集合的创建

python 复制代码
s = set()  # 空集合
d = {}     # 空字典

10. 性能特点

  • 查找、插入、删除:平均时间复杂度 O(1)
  • 空间复杂度:O(n)
  • 适合:需要快速成员检查、去重的场景
  • 不适合:需要保持顺序或索引访问的场景

总结

本文主要对python的基本数据类型中的可变数据类型进行相关的学习,感谢大家的关注,一起努力学习。

资料关注

相关资料获取:

公众号:咚咚王

《Python编程:从入门到实践》

《利用Python进行数据分析》

《算法导论中文第三版》

《概率论与数理统计(第四版) (盛骤) 》

《程序员的数学》

《线性代数应该这样学第3版》

《微积分和数学分析引论》

《(西瓜书)周志华-机器学习》

《TensorFlow机器学习实战指南》

《Sklearn与TensorFlow机器学习实用指南》

《模式识别(第四版)》

《深度学习 deep learning》伊恩·古德费洛著 花书

《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》

《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen) 》

《自然语言处理综论 第2版》

《Natural-Language-Processing-with-PyTorch》

《计算机视觉-算法与应用(中文版)》

《Learning OpenCV 4》

《AIGC:智能创作时代》杜雨+&+张孜铭

《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》

《从零构建大语言模型(中文版)》

《实战AI大模型》

《AI 3.0》