跳到主要内容
Python 基础教程:循环控制与核心数据结构详解 | 极客日志
Python 算法
Python 基础教程:循环控制与核心数据结构详解 深入讲解 Python 中的列表(List)和字典(Dictionary)两种核心数据结构,涵盖创建、访问、增删改查及切片操作。同时详细剖析 for 循环与 while 循环的语法、应用场景及进阶技巧(如 enumerate、zip、嵌套循环),并通过代码示例对比两者的区别与选择指南,帮助读者掌握数据流转与自动化处理的核心法则。
星云 发布于 2026/3/30 更新于 2026/5/29 25 浏览引言
想象一下,你要管理一个繁忙的快递站。
列表(List) 就像那一排排整齐的货架,每个格子上放着一个包裹(元素),你有它们的顺序编号(索引)。你可以快速找到第 5 个货架上的东西,也可以轻松地在末尾新增一个包裹。
字典(Dictionary) 则像是一个智能查询系统。每个包裹都有一个独一无二的单号(键),通过这个单号,你能瞬间查到它的所有详细信息(值)。找'QG211314'这个包裹?不需要知道它放在第几个,直接问系统就行。
那么循环呢?
for循环 就像你沿着货架从头到尾 依次检查每一个包裹('遍历'),这是你知道要处理所有物品 时的首选。
while循环 则像是一个'直到…才停止'的指令。比如,'直到 货架清空,才停止搬运'。你并不一开始就知道要循环多少次,而是由一个条件 来决定的。
在 Python 的世界里,几乎每一个有趣的项目,都离不开这四者的精妙配合。本文将带你深入这个'快递站',掌握让数据流转自如的核心法则。
列表(List)
1. 拿生活类比
想象一下你去超市购物的情景。你推着一辆购物车,里面按顺序放着:牛奶、面包、鸡蛋、苹果 。
在 Python 中,这个购物车就是一个列表(List) :
shopping_list = ['牛奶' , '面包' , '鸡蛋' , '苹果' ]
列表的本质 :一个有序 、可变 的元素集合,像是给你的数据物品准备的一排编号货架。
2. 创建列表的多种方式
fruits = ['苹果' , '香蕉' , '橙子' ]
numbers = [1 , 2 , 3 , 4 , 5 ]
mixed = [1 , 'hello' , 3.14 , True ]
chars = list ('Python' )
range_list = list (range ( ))
5
3. 访问列表元素 列表使用索引(index) 来定位元素,索引从 0 开始!
colors = ['红' , '橙' , '黄' , '绿' , '青' , '蓝' , '紫' ]
print (colors[0 ])
print (colors[3 ])
print (colors[-1 ])
print (colors[-2 ])
length = len (colors)
last_index = length - 1
4. 列表的'增删改查'操作 todo_list = ['学习 Python' , '玩游戏' ]
todo_list.append('运动' )
todo_list.insert(1 , '吃午饭' )
todo_list.extend(['阅读' , '休息' ])
todo_list.remove('吃午饭' )
del todo_list[0 ]
popped_item = todo_list.pop()
popped_item = todo_list.pop(1 )
todo_list.clear()
colors = ['红' , '橙' , '黄' ]
colors[1 ] = '粉红'
colors = ['红' , '橙' , '黄' , '绿' , '蓝' ]
if '绿' in colors:
print ("绿色在列表中!" )
index = colors.index('黄' )
count = colors.count('红' )
5. 切片与遍历 numbers = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
print (numbers[2 :6 ])
print (numbers[:5 ])
print (numbers[5 :])
print (numbers[::2 ])
print (numbers[::-1 ])
first_five = numbers[:5 ]
fruits = ['苹果' , '香蕉' , '橙子' ]
for fruit in fruits:
print (f"我喜欢吃{fruit} " )
for index, fruit in enumerate (fruits):
print (f"第{index} 个水果是:{fruit} " )
6. 动手练习
text = "apple banana apple orange banana apple"
words = text.split()
字典(Dictionary)
1. 从列表的局限到字典的诞生 咱们刚刚学了列表,想象这样一个场景:你需要管理一个班级的学生信息。用列表可以这样写:
students = ['张三' , 18 , '男' , '李四' , 19 , '女' , '王五' , 20 , '男' ]
问题来了 :你怎么快速找到'李四'的年龄?你得记住年龄在列表中的位置,然后通过 students[4] 来获取。如果数据再多一些,这种'位置记忆'就变得极其困难。
student = {'姓名' : '张三' , '年龄' : 18 , '性别' : '男' }
字典的本质 :一种键值对(key-value) 的映射结构,让你能通过一个有意义的关键词(键) 快速找到对应的数据(值) 。
2. 拿生活类比
键(Key) = 要查的单词(如"apple")
值(Value) = 单词的解释(如"苹果")
键(Key) = 快递单号(如"SF123456")
值(Value) = 快递信息(收货人、地址、包裹内容)
在 Python 中,字典就是这样一个高效的查询系统 。
3. 创建字典的各种方法 student = {'姓名' : '张三' , '年龄' : 18 , '专业' : '计算机' }
book = {'标题' : 'Python 编程' , '价格' : 89.9 , '库存' : True }
empty_dict = dict ()
person = dict (name='李四' , age=25 )
pairs = [('姓名' , '王五' ), ('年龄' , 20 )]
person = dict (pairs)
squares = {x: x**2 for x in range (5 )}
valid_keys = {
'字符串' : 'value1' ,
123 : 'value2' ,
(1 , 2 , 3 ): 'value3' ,
}
4. 访问字典 student = {'姓名' : '张三' , '年龄' : 18 , '专业' : '计算机' }
print (student['姓名' ])
print (student['年龄' ])
address = student.get('地址' )
address = student.get('地址' , '未填写' )
方法 3:setdefault() - 获取值 ,如果不存在则设置默认值(非常实用!一行代码完成'如果不存在则初始化')
student.setdefault('成绩' , [])
student['成绩' ].append(95 )
5. 字典的'增删改查'操作 config = {'主题' : '暗色' , '语言' : '中文' }
config['字体大小' ] = 14
config['主题' ] = '亮色'
config.update({'语言' : '英文' , '声音' : True })
language = config.pop('语言' )
方法 3:popitem() - 删除最后插入的键值对 (Python 3.7+有序)
last_item = config.popitem()
employee = {'姓名' : '王五' , '部门' : '技术部' , '工号' : 1001 }
keys = employee.keys()
values = employee.values()
items = employee.items()
key_list = list (employee.keys())
6. 字典的高级技巧
squares = {x: x**2 for x in range (1 , 6 )}
scores = {'张三' : 85 , '李四' : 92 , '王五' : 78 , '赵六' : 95 }
high_scores = {name: score for name, score in scores.items() if score >= 90 }
inverted = {score: name for name, score in scores.items()}
dict1 = {'a' : 1 , 'b' : 2 }
dict2 = {'b' : 3 , 'c' : 4 }
merged = dict1 | dict2
from collections import defaultdict
words = ['apple' , 'banana' , 'apple' , 'orange' , 'banana' , 'apple' ]
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else :
word_count[word] = 1
word_count = defaultdict(int )
for word in words:
word_count[word] += 1
7. 字典 vs 列表:何时选择谁? 特性 列表(List) 字典(Dictionary) 核心概念 有序集合 键值对映射 访问方式 数字索引(0,1,2…) 任意不可变键 顺序 保持插入顺序(重要!) Python 3.7+ 保持插入顺序 查找速度 O(n)(线性搜索) O(1)(平均,哈希表) 内存占用 较小 较大(需要存储键和值) 典型用途 有序数据序列 关联数据、快速查找
需要维护顺序 且通过位置访问 → 列表
需要通过特定标识符快速查找 → 字典
数据是同质的 (同一类型) → 考虑列表
数据是异质的 (不同类型) → 考虑字典
8. 动手练习
sales = [
{'product' : 'A' , 'amount' : 100 , 'month' : 'Jan' },
{'product' : 'B' , 'amount' : 150 , 'month' : 'Jan' },
{'product' : 'A' , 'amount' : 200 , 'month' : 'Feb' },
{'product' : 'C' , 'amount' : 50 , 'month' : 'Feb' },
]
for 循环
1. 从重复劳动到自动化 想象一下,你需要给公司 100 名员工发送生日祝福邮件。手动操作需要:
找到第一个员工的邮箱 → 写邮件 → 发送
找到第二个员工的邮箱 → 写邮件 → 发送
…(重复 98 次)
这种重复模式在编程中太常见了!幸运的是,Python 为我们提供了 for 循环 ——让计算机自动处理重复任务的完美工具。
for 员工编号 in range (1 , 101 ):
print (f"你好,员工{员工编号} !" )
for 循环的本质 :一种确定性循环 ,用于遍历序列中的每个元素 并执行相同的操作。
2. for 循环的基本语法 for 变量 in 可迭代对象:
执行操作 (变量)
fruits = ['苹果' , '香蕉' , '橙子' , '葡萄' ]
for fruit in fruits:
print (f"我喜欢吃{fruit} " )
print ("---" )
print ("所有水果都展示完了!" )
3. for 循环的'能量源':可迭代对象 for 循环可以遍历任何'可迭代对象' ,主要包括:
scores = [85 , 92 , 78 , 90 , 88 ]
total = 0
for score in scores:
total += score
print (f"总分:{total} " )
print (f"平均分:{total / len (scores)} " )
text = "Hello, Python!"
vowel_count = 0
for char in text:
if char.lower() in 'aeiou' :
vowel_count += 1
print (f"元音字母个数:{vowel_count} " )
student = {'姓名' : '张三' , '年龄' : 18 , '专业' : '计算机' }
for key in student:
print (f"键:{key} " )
for value in student.values():
print (f"值:{value} " )
for key, value in student.items():
print (f"{key} :{value} " )
for i in range (5 ):
print (i)
for i in range (2 , 6 ):
print (i)
for i in range (0 , 10 , 2 ):
print (i)
for i in range (5 , 0 , -1 ):
print (i)
colors = ('红' , '绿' , '蓝' )
for color in colors:
print (color)
unique_numbers = {1 , 2 , 3 , 3 , 2 }
for num in unique_numbers:
print (num)
with open ('data.txt' , 'r' , encoding='utf-8' ) as file:
for line in file:
print (line.strip())
4. for 循环的进阶技巧 fruits = ['苹果' , '香蕉' , '橙子' ]
index = 0
for fruit in fruits:
print (f"第{index} 个水果:{fruit} " )
index += 1
for index, fruit in enumerate (fruits):
print (f"第{index} 个水果:{fruit} " )
for index, fruit in enumerate (fruits, start=1 ):
print (f"第{index} 个水果:{fruit} " )
names = ['张三' , '李四' , '王五' ]
scores = [85 , 92 , 78 ]
subjects = ['数学' , '语文' , '英语' ]
for name, score in zip (names, scores):
print (f"{name} 的成绩是{score} 分" )
for name, score, subject in zip (names, scores, subjects):
print (f"{name} 的{subject} 成绩是{score} 分" )
list1 = [1 , 2 , 3 ]
list2 = ['a' , 'b' ]
for num, char in zip (list1, list2):
print (num, char)
print ("乘法表:" )
for i in range (1 , 4 ):
for j in range (1 , 4 ):
print (f"{i} × {j} = {i * j} " , end="\t" )
print ()
4. 循环控制:break、continue、else
numbers = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
for num in numbers:
if num > 5 :
break
print (num)
for num in range (1 , 11 ):
if num % 2 == 0 :
continue
print (num)
for num in range (3 ):
print (num)
else :
print ("循环正常结束!" )
for num in range (3 ):
if num == 1 :
break
print (num)
else :
print ("循环正常结束!" )
squares = []
for i in range (1 , 6 ):
squares.append(i ** 2 )
squares = [i ** 2 for i in range (1 , 6 )]
even_squares = [i ** 2 for i in range (1 , 11 ) if i % 2 == 0 ]
squares_dict = {i: i ** 2 for i in range (1 , 6 )}
unique_lengths = {len (word) for word in ['apple' , 'banana' , 'apple' , 'orange' ]}
5. 动手练习
text = """ Python 是一种高级编程语言,由 Guido van Rossum 于 1991 年创建。
它以简洁、易读的语法而闻名,广泛应用于 Web 开发、数据科学、人工智能等领域。 """
import random
import string
def generate_passwords (count, length=8 ):
passwords = []
return passwords
print (generate_passwords(3 , 10 ))
while 循环
1. 引入:当你不确定需要循环多少次时 想象这样一个场景:你在开发一个猜数字游戏,程序随机生成一个 1-100 的数字,玩家不断猜测,直到猜中为止。你无法提前知道 玩家需要猜多少次——可能 1 次就中,也可能要猜 50 次。
import random
target_number = random.randint(1 , 100 )
guess_count = 0
while True :
guess = int (input ("请猜一个 1-100 的数字:" ))
guess_count += 1
if guess < target_number:
print ("猜小了!" )
elif guess > target_number:
print ("猜大了!" )
else :
print (f"恭喜!你猜了{guess_count} 次就猜中了!" )
break
while 循环的本质 :一种条件控制循环 ,只要条件为真就不断重复执行。它适用于循环次数不确定,但知道继续条件 的场景。
2. while 循环的基本语法
count = 0
while count < 5 :
print (f"当前计数:{count} " )
count += 1
print ("循环结束!" )
3. while 循环的核心要素:条件控制
progress = 0
total = 100
while progress < total:
progress += 10
print (f"加载中... {progress} %" )
print ("加载完成!" )
is_valid = False
while not is_valid:
age_input = input ("请输入年龄 (0-120): " )
if age_input.isdigit():
age = int (age_input)
if 0 <= age <= 120 :
is_valid = True
print (f"年龄验证通过:{age} " )
else :
print ("年龄必须在 0-120 之间!" )
else :
print ("请输入有效的数字!" )
print ("继续处理其他逻辑..." )
scores = []
print ("请输入学生成绩 (输入 -1 结束):" )
while True :
score_input = input ("成绩:" )
if score_input == "-1" :
break
if score_input.isdigit():
score = int (score_input)
scores.append(score)
else :
print ("请输入数字!" )
print (f"共收集{len (scores)} 个成绩,平均分:{sum (scores)/len (scores):.2 f} " )
4. while 循环的高级技巧
count = 0
while count < 3 :
print (f"尝试第{count+1 } 次" )
count += 1
else :
print ("所有尝试都完成了!" )
count = 0
while count < 5 :
if count == 3 :
print ("提前结束!" )
break
print (count)
count += 1
else :
print ("这不会执行" )
attempts = 0
max_attempts = 3
success = False
while not success and attempts < max_attempts:
attempts += 1
print (f"第{attempts} 次尝试..." )
import random
success = random.random() > 0.7
if success:
print ("操作成功!" )
elif attempts == max_attempts:
print ("已达最大尝试次数,操作失败!" )
fruits = ['苹果' , '香蕉' , '橙子' ]
for fruit in fruits:
print (fruit)
index = 0
while index < len (fruits):
print (fruits[index])
index += 1
print ("九九乘法表:" )
row = 1
while row <= 9 :
col = 1
while col <= row:
print (f"{col} ×{row} ={col*row:2d} " , end=" " )
col += 1
print ()
row += 1
5. 无限循环与如何避免
count = 0
while count < 5 :
print (count)
while True :
user_input = input ("输入'quit'退出:" )
if user_input.lower() == 'quit' :
break
print (f"你输入了:{user_input} " )
max_iterations = 1000
iteration = 0
while iteration < max_iterations:
iteration += 1
if some_condition:
break
if iteration == max_iterations:
print ("警告:达到最大循环次数!" )
6. for 循环与 while 循环的区别 特性 for 循环 while 循环 循环条件 遍历可迭代对象 满足条件时继续 循环次数 确定(由序列长度决定) 不确定 适用场景 遍历已知集合 条件满足时重复 控制方式 自动迭代 需手动更新条件 死循环风险 较低 较高(需谨慎)
知道要循环多少次或遍历什么 → for 循环
不知道循环次数,但知道继续的条件 → while 循环
for student in students:
process_student(student)
user_input = ""
while user_input.lower() != "quit" :
user_input = input ("请输入命令:" )
process_command(user_input)
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
Gemini 图片去水印 基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
Markdown转HTML 将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online