企业文化

让建站和SEO变得简单

让不懂建站的用户快速建站,让会建站的提高建站效率!

东说念主工智能之编程基础 Python 初学: 第六章 基本数据类型

点击次数:72 发布日期:2025-12-21 15:34

东说念主工智能之编程基础 Python 初学

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

绪言

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

List(列表)

在 Python 中,列表(List) 是一种有序、可变的序列数据类型。它是 Python 最常用和最生动的数据结构之一,不错存储大肆类型的对象(整数、字符串、其他列表等),何况允许叠加元素。

1. 列表的创建

# 使用方括号 []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. 列表的脾气

3. 列表的拜谒

索引(Indexing)

fruits = ["apple", "banana", "cherry"]print(fruits[0]) # apple (第一个)print(fruits[-1]) # cherry (临了一个)# print(fruits[10]) # IndexError: list index out of range

切片(Slicing)

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. 列表的修改(可变性)

修改元素

fruits[1] = "blueberry"print(fruits) # ['apple', 'blueberry', 'cherry']

添加元素

# append - 在末尾添加单个元素fruits.append("grape")# insert - 在指定位置插入元素fruits.insert(1, "kiwi") # 在索引1处插入# extend - 添增加个元素(另一个可迭代对象)fruits.extend(["mango", "pineapple"])

删除元素

# remove - 删除第一个匹配的值fruits.remove("apple")# pop - 删除并复返指定索引的元素(默许临了一个)last_fruit = fruits.popsecond_fruit = fruits.pop(1)# del - 删除指定索引或切片del fruits[0]del fruits[1:3] # 删除索引1到2的元素# clear - 清空列表# fruits.clear

5. 常用列表纪律

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. 列表操作

拼接

list1 = [1, 2]list2 = [3, 4]combined = list1 + list2 # [1, 2, 3, 4]

叠加

repeated = [1, 2] * 3 # [1, 2, 1, 2, 1, 2]

成员查验

if "apple" in fruits: print("找到了苹果!")

长度

length = len(fruits)

7. 列表推导式(List Comprehension)

一种简约创建列表的式样。

# 创建平常数列表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. 遍历列表

# 纪律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. 嵌套列表

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

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. 可变对象的援用

# ❌ 颠倒:分享吞并个列表对象list_of_lists = [[]] * 3list_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. 修改列表时的索引问题

# ❌ 在遍历中删除元素可能导致跳过元素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 元组

Dictionary(字典)

在 Python 中,字典(Dictionary) 是一种异常纷乱且常用的数据结构,用于存储键值对(key-value pairs)。它也被称为相干数组或哈希表。

1. 字典的创建

# 使用花括号 {}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. 字典的脾气

3. 字典的基本操作

拜谒值

person = {"name": "Alice", "age": 25}# 使用方括号 []print(person["name"]) # Alice# 使用 get 纪律(保举,更安全)print(person.get("age")) # 25print(person.get("gender")) # None (默许)print(person.get("gender", "未知")) # "未知" (指定默许值)

添加/修改元素

# 添加新键值对person["city"] = "Shanghai"# 修改现存值person["age"] = 26# 使用 update 批量更新person.update({"job": "Engineer", "salary": 10000})

删除元素

# pop - 删除并复返指定键的值age = person.pop("age")# popitem - 删除并复返临了一个键值对 (Python 3.7+)last_item = person.popitem# del - 删除指定键del person["city"]# clear - 清空字典# person.clear

4. 字典的常用纪律

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. 遍历字典

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. 字典推导式

访佛于列表推导式,不错简约地创建字典。

# 创建平常数字典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. 嵌套字典

字典的值不错是另一个字典,用于示意复杂的数据结构。

students = { "Alice": { "age": 20, "grade": "A", "courses": ["Math", "Physics"] }, "Bob": { "age": 21, "grade": "B", "courses": ["Chemistry", "Biology"] }}# 拜谒嵌套值print(students["Alice"]["age"]) # 20print(students["Bob"]["courses"][0]) # Chemistry# 遍历嵌套字典for name, info in students.items: print(f"{name}: {info['age']}岁, 得益{info['grade']}")

8. 实用手段和最好实施

1. 使用

# ❌ 可能出错# value = my_dict["missing_key"]# 安全的作念法value = my_dict.get("missing_key", "默许值")

2. 竖立默许值

# setdefault - 若是键不存在,则竖立默许值person.setdefault("gender", "未知")# 若是"gender"键不存在,则添加并赋值"未知"# defaultdict - 更高档的默许字典from collections import defaultdictword_count = defaultdict(int) # 默许值为0word_count["apple"] += 1 # 即使键不存在也不会报错

3. 合并字典(Python 3.9+)

9. 醒目事项

1. 可哈希的键

# 有用的键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. 浅拷贝问题

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

10. 字典的应用场景

1. 建树料理

config = { "host": "localhost", "port": 8080, "debug": True}

2. 缓存

cache = {}def get_data(key): if key in cache: return cache[key] # 盘算数据... cache[key] = result return result

3. 计数器

word_count = {}for word in words: word_count[word] = word_count.get(word, 0) + 1

4. JSON 数据处理

import jsondata = json.loads('{"name": "Alice", "age": 25}')

Set(累积)

在 Python 中,累积(Set) 是一种无序、可变的容器数据类型,用于存储独一的元素(即不包含叠加项)。累积基于数学中的累积论,补助错乱、并集、差集等操作。

1. 累积的创建

# 使用花括号 {} - 醒目:空累积不行用 {}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. 累积的脾气

3. 累积的基本操作

添加元素

fruits = {"apple", "banana"}# add - 添加单个元素fruits.add("orange")# update - 添增加个元素(任何可迭代对象)fruits.update(["grape", "kiwi"])fruits.update("xyz") # 添加 'x', 'y', 'z'

删除元素

# remove - 删除指定元素,元素不存在时会报错fruits.remove("banana")# discard - 删除指定元素,元素不存在时不会报错(保举)fruits.discard("mango") # 即使莫得也不会报错# pop - 立时删除并复返一个元素(因为无序)random_fruit = fruits.pop# clear - 清空累积# fruits.clear

查验成员

if "apple" in fruits: print("苹果在聚辘集")if "mango" not in fruits: print("莫得芒果")

获得大小

size = len(fruits)

4. 累积的数学运算

累积补助丰富的累积运算:

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 = set3) # True (set1 是 set3 的超集)

5. 累积推导式

访佛于列表推导式,不错简约地创建累积。

# 创建平常数累积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 是累积的不可变版块,创建后不行修改,因此它是可哈希的,不错用作字典的键或累积的元素。

# 创建 frozensetfrozen = 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. 遍历累积

由于累积无序,遍历礼貌不固定。

fruits = {"apple", "banana", "orange"}for fruit in fruits: print(fruit)# 若是需要排序输出for fruit in sorted(fruits): print(fruit)

8. 本色应用示例

1. 去除叠加元素

# 最常用的用途original_list = [1, 2, 2, 3, 3, 3, 4]unique_list = list(set(original_list))print(unique_list) # [1, 2, 3, 4] (礼貌可能不同)

2. 成员经历测试(高效)

# 累积的查找时辰复杂度为 O(1),比列表 O(n) 快得多valid_users = {"alice", "bob", "charlie"}def check_access(username): return username in valid_users # 异常快

3. 文本处理

text = "hello world python"vowels = set("aeiou")text_chars = set(text)# 找出文本中包含的元音字母found_vowels = text_chars & vowelsprint(found_vowels) # {'o', 'e'}

4. 相比数据集

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. 可变元素不行放入累积

# ❌ 颠倒:列表是可变的,不可哈希# invalid_set = {[1, 2], [3, 4]} # TypeError# 正确:使用元组(不可变)valid_set = {(1, 2), (3, 4)}

2. 累积本人不可哈希

# ❌ 颠倒# dict_with_set = {{"a", "b"}: "value"} # TypeError# 正确:使用 frozensetdict_with_frozen = {frozenset(["a", "b"]): "value"}

3. 空累积的创建

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》