当前位置: 首页 > news >正文

Python中`for`循环的简单使用示例

在Python中,for循环是一种常用的控制结构,用于遍历序列(如列表、元组、字符串等)或其他可迭代对象。以下是for循环的基本用法和一些常见场景的示例。


基本语法

for 变量 in 可迭代对象:
    # 循环体
  • 变量:每次循环时,变量会被赋值为可迭代对象中的当前元素。
  • 可迭代对象:可以是列表、元组、字符串、字典、集合、文件对象等。

示例 1:遍历列表

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

输出:

apple
banana
cherry

示例 2:遍历字符串

for char in "Python":
    print(char)

输出:

P
y
t
h
o
n

示例 3:遍历字典

person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
    print(f"{key}: {value}")

输出:

name: Alice
age: 25
city: New York

示例 4:使用range()函数

range()生成一个整数序列,常用于循环指定次数。

for i in range(5):  # 0 到 4
    print(i)

输出:

0
1
2
3
4

示例 5:遍历文件内容

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() 去掉换行符

示例 6:嵌套循环

for i in range(3):  # 外层循环
    for j in range(2):  # 内层循环
        print(f"i={i}, j={j}")

输出:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

示例 7:使用enumerate()获取索引和值

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

输出:

Index 0: apple
Index 1: banana
Index 2: cherry

示例 8:使用zip()遍历多个序列

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

输出:

Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

示例 9:遍历时使用else子句

for循环可以有一个else子句,当循环正常结束时执行(即没有被break中断)。

for i in range(3):
    print(i)
else:
    print("Loop finished")

输出:

0
1
2
Loop finished

示例 10:遍历文件夹中的文件

import os

directory = "/path/to/your/directory"
for filename in os.listdir(directory):
    if os.path.isfile(os.path.join(directory, filename)):
        print(filename)

总结

  • for循环是Python中遍历可迭代对象的主要方式。
  • 结合range()enumerate()zip()等函数,可以实现更复杂的逻辑。
  • for循环可以与elsebreakcontinue等语句配合使用。
http://www.dtcms.com/a/57072.html

相关文章:

  • 数据结构链式表
  • 结合 Pandas 使用 SQLite3 实战
  • 大白话JavaScript实现一个函数,将数组中的元素进行去重
  • SPI驱动五) -- SPI_DAC上机实验(使用spidev)
  • 事务-Transaction
  • EXCEL自动化13 | 批量重命名工作簿中的工作表
  • 【AD】5-15 Active Route的自动布线辅助
  • postman接口请求中的 Raw是什么
  • 【愚公系列】《Python网络爬虫从入门到精通》045-Charles的SSL证书的安装
  • AIP-161 域掩码
  • AI 时代的新宠儿:向量数据库
  • 渗透测试之利用sql拿shell(附完整流程+防御方案)
  • 深度学习笔记——CNN卷积神经网络
  • Python----数据可视化(Seaborn一:介绍,应用)
  • css动画
  • GetWindowLongPtr函数分析
  • OpenCV 拆分、合并图像通道方法及复现
  • nginx的安装以及相关的全局性配置
  • K8s面试题总结(十一)
  • 使用Arduino和ESP8266进行基于物联网的垃圾箱监控
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_cycle_modules
  • 哈夫曼树的讲解
  • 【微知】如何命令行查看Linux上连接的Wi-Fi信息?(iw dev wlp4s0 link ; information wireless)
  • 基于大数据的商品数据可视化及推荐系统
  • C++11新特性 5.static静态
  • 【数据结构初阶】---堆的实现、堆排序以及文件中的TopK问题
  • MySQL(单表)知识点
  • 蓝耘智算 + 通义万相 2.1:为 AIGC 装上 “智能翅膀”,翱翔创作新天空
  • 代码随想录-训练营-day46
  • ES语法学习