高效使用Python的for循环需理解其迭代器机制,利用列表推导式提升性能,结合enumerate获取索引,用range控制循环次数,善用break和continue控制流程,并避免修改被遍历列表等常见错误。

Python中的
for
for
for
for
enumerate
解决方案:
立即学习“Python免费学习笔记(深入)”;
基本语法
for
for item in iterable:
# 执行代码块item
iterable
循环列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)输出:
apple banana cherry
循环字符串
message = "Hello"
for char in message:
print(char)输出:
H e l l o
循环字典
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
for key, value in student.items():
print(f"{key}: {value}")输出:
name: Alice age: 20 major: Computer Science
使用 range()
range()
for i in range(5): # 生成 0, 1, 2, 3, 4
print(i)输出:
0 1 2 3 4
break
continue
break
continue
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break # 终止循环
print(num)输出:
1 2
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue # 跳过当前迭代
print(num)输出:
1 2 4 5
else
for
else
break
numbers = [1, 2, 4, 5]
for num in numbers:
if num == 3:
print("Found 3")
break
else:
print("3 not found")输出:
3 not found
初学者容易犯一些错误,比如修改循环中的列表导致索引错乱,或者在不理解迭代器的情况下使用
for
索引越界
my_list = [1, 2, 3]
for i in range(len(my_list)):
print(my_list[i]) # 正确
# for i in range(len(my_list) + 1): # 错误:会导致索引越界
# print(my_list[i])修改循环中的列表
my_list = [1, 2, 3, 4, 5]
new_list = []
for item in my_list:
if item % 2 == 0:
new_list.append(item * 2)
print(new_list) # 输出 [4, 8]不正确的迭代器使用
for
# my_number = 123 # 错误:整数不可迭代
# for digit in my_number:
# print(digit)
my_string = "123" # 正确:字符串可迭代
for digit in my_string:
print(digit)忘记冒号
for
:
for
my_list = [1, 2, 3]
for item in my_list: # 正确
print(item)
# for item in my_list # 错误:缺少冒号
# print(item)在数据处理领域,
for
if
for
for
数据过滤
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_data = []
for item in data:
if item % 2 == 0: # 筛选偶数
filtered_data.append(item)
print(filtered_data) # 输出 [2, 4, 6, 8, 10]数据转换
data = [1, 2, 3, 4, 5]
squared_data = []
for item in data:
squared_data.append(item ** 2) # 计算平方
print(squared_data) # 输出 [1, 4, 9, 16, 25]数据聚合
data = [1, 2, 3, 4, 5]
total = 0
for item in data:
total += item # 计算总和
average = total / len(data) # 计算平均值
print(f"Total: {total}, Average: {average}") # 输出 Total: 15, Average: 3.0读取文件数据
with open("data.txt", "r") as file:
for line in file:
line = line.strip() # 去除行尾空格
print(line)如果
data.txt
apple banana cherry
输出:
apple banana cherry
数据分析示例:统计词频
text = "this is a test string this is a string"
words = text.split()
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(word_counts) # 输出 {'this': 2, 'is': 2, 'a': 2, 'test': 1, 'string': 2}以上就是python怎么用for循环_python循环语句入门教程的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号