Python 遍历列表的多种方法_python怎么遍历列

Python 遍历列表的多种方法_python怎么遍历列

编码文章call10242025-10-22 21:53:261A+A-

在 Python 中,遍历列表有多种方式,下面详细介绍各种方法:

1. 基本的 for 循环遍历


# 定义一个水果列表,后续将对其元素进行直接遍历操作
fruits = ['apple', 'banana', 'orange', 'grape']

# 通过 for 循环直接遍历列表中的元素
for fruit in fruits:
    print(fruit)

# 以下为上述代码运行后的输出示例
# apple
# banana
# orange
# grape



2. 使用 enumerate() 获取索引和值

# 定义一个包含多种水果名称的列表
fruits = ['apple', 'banana', 'orange', 'grape']

# 运用 enumerate 函数,同时获取列表元素的索引以及元素本身
for index, fruit in enumerate(fruits):
    print(f"索引 {index}: {fruit}")

# 以下为上述代码运行后的输出示例
# 索引 0: apple
# 索引 1: banana
# 索引 2: orange
# 索引 3: grape

# 值得注意的是,enumerate 函数可以指定起始索引
for index, fruit in enumerate(fruits, start=1):
    print(f"第 {index} 个水果: {fruit}")


3. 使用 range() 和 len() 通过索引遍历


# 构建一个水果列表,其中囊括了苹果、香蕉、橙子和葡萄
fruits = ['apple', 'banana', 'orange', 'grape']

# 借助 range 函数和列表长度,通过索引遍历列表元素
for i in range(len(fruits)):
    print(f"fruits[{i}] = {fruits[i]}")

# 以下展示了上述代码执行后的输出结果
# fruits[0] = apple
# fruits[1] = banana
# fruits[2] = orange
# fruits[3] = grape


4. 使用 while 循环遍历


# 定义一个包含多种水果名称的列表
fruits = ['apple', 'banana', 'orange', 'grape']

# 初始化索引变量
i = 0

# 运用 while 循环,依据索引逐一遍历列表中的水果元素
while i < len(fruits):
    print(fruits[i])
    # 索引递增,以便访问下一个元素
    i += 1


5. 使用列表推导式(创建新列表)


# 定义一个水果列表,其中包含了苹果、香蕉、橙子和葡萄
fruits = ['apple', 'banana', 'orange', 'grape']

# 利用列表推导式创建一个新的列表,将原列表中所有水果名称转换为大写形式
uppercase_fruits = [fruit.upper() for fruit in fruits]
print(uppercase_fruits)

# 以下为上述操作的输出结果
# ['APPLE', 'BANANA', 'ORANGE', 'GRAPE']

# 运用带条件的列表推导式,筛选出名称长度超过 5 个字符的水果
long_fruits = [fruit for fruit in fruits if len(fruit) > 5]
print(long_fruits)

# 以下为该操作的输出结果
# ['banana', 'orange']


6. 使用 zip() 同时遍历多个列表


# 定义水果名称列表,包含苹果、香蕉和橙子
fruits = ['apple', 'banana', 'orange']
# 定义对应水果的单价列表
prices = [2.5, 1.8, 3.0]
# 定义对应水果的数量列表
quantities = [10, 15, 8]

# 利用 zip 函数将水果名称、单价和数量一一对应,进行遍历
for fruit, price, quantity in zip(fruits, prices, quantities):
    # 计算每种水果的总价
    total = price * quantity
    # 输出每种水果的名称、单价、数量和总价信息
    print(f"{fruit}: 单价 ${price}, 数量 {quantity}, 总价 ${total}")

# 以下为上述代码的输出结果
# apple: 单价 $2.5, 数量 10, 总价 $25.0
# banana: 单价 $1.8, 数量 15, 总价 $27.0
# orange: 单价 $3.0, 数量 8, 总价 $24.0


7. 使用 reversed() 反向遍历


# 构建一个水果列表,其中包含了苹果、香蕉、橙子和葡萄
fruits = ['apple', 'banana', 'orange', 'grape']

# 采用 reversed 函数对列表进行反向遍历操作
for fruit in reversed(fruits):
    print(fruit)

# 以下呈现了上述代码执行后的输出内容
# grape
# orange
# banana
# apple


8. 使用 sorted() 按顺序遍历


# 定义一个水果列表,其中收纳了苹果、香蕉、橙子和葡萄这几种常见水果
fruits = ['apple', 'banana', 'orange', 'grape']

# 运用 sorted 函数以字母顺序对水果列表进行遍历
# 此操作会将列表元素按字母先后顺序依次排列并遍历输出
for fruit in sorted(fruits):
    print(fruit)

# 以下为按字母顺序遍历后的输出结果
# apple
# banana
# grape
# orange

# 采用 sorted 函数并指定 key 为 len,按照字符串长度对水果列表进行排序遍历
# 该操作会依据水果名称字符串的长度从小到大排列并遍历输出
for fruit in sorted(fruits, key=len):
    print(fruit)

# 以下为按字符串长度排序遍历后的输出结果
# apple
# grape
# banana
# orange


9. 使用 iter() 和 next() 手动控制迭代


# 构建一个水果列表,其中囊括了苹果、香蕉、橙子和葡萄等常见水果
fruits = ['apple', 'banana', 'orange', 'grape']

# 借助 iter 函数创建一个可迭代对象,用于逐个访问水果列表中的元素
fruit_iter = iter(fruits)

try:
    # 运用 while 循环持续从可迭代对象中获取下一个元素
    while True:
        fruit = next(fruit_iter)
        print(fruit)
except StopIteration:
    # 当可迭代对象中的元素全部遍历完毕,捕获 StopIteration 异常并输出提示信息
    print("遍历结束")

# 以下为上述代码执行后的输出结果
# apple
# banana
# orange
# grape
# 遍历结束


10. 遍历嵌套列表


# 构建一个二维列表,此列表可看作一个 3x3 的矩阵,包含了 1 到 9 的数字
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# 方法 1:采用直接遍历的方式访问二维列表的元素
# 外层循环遍历矩阵的每一行
for row in matrix:
    # 内层循环遍历当前行的每一个元素
    for element in row:
        # 输出当前元素,元素间以空格分隔
        print(element, end=' ')
    # 每一行元素输出完毕后,进行换行操作
    print()

# 以下为方法 1 执行后的输出结果
# 1 2 3
# 4 5 6
# 7 8 9

# 方法 2:利用 enumerate 函数进行遍历
# enumerate 函数可同时获取元素的索引和值
# 外层循环获取行的索引 i 和行内容 row
for i, row in enumerate(matrix):
    # 内层循环获取元素的列索引 j 和元素值 element
    for j, element in enumerate(row):
        # 输出元素在矩阵中的位置及元素值
        print(f"matrix[{i}][{j}] = {element}")


11. 使用 filter() 过滤遍历


# 构建一个包含从 1 到 10 整数的数字列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 运用 filter 函数与 lambda 表达式,仅对列表中的偶数进行遍历
# filter 函数会根据 lambda 表达式定义的条件筛选出符合要求的元素
# 这里的条件是元素能被 2 整除,即该元素为偶数
for even_num in filter(lambda x: x % 2 == 0, numbers):
    # 输出筛选出的偶数
    print(even_num)

# 以下为上述代码执行后的输出结果
# 2
# 4
# 6
# 8
# 10


12. 使用 map() 转换后遍历


# 构建一个包含 1 至 5 整数的数字列表
numbers = [1, 2, 3, 4, 5]

# 借助 map 函数与 lambda 表达式,对列表中的每个元素进行平方运算,并遍历这些平方数
# map 函数会将 lambda 表达式应用于列表中的每一个元素
# 此处的 lambda 表达式定义了对元素进行平方操作
for squared in map(lambda x: x**2, numbers):
    # 输出经过平方运算后的结果
    print(squared)

# 以下为上述代码执行后的输出结果
# 1
# 4
# 9
# 16
# 25


选择建议

  • 大多数情况:使用基本的

for item in list 方式

  • 需要索引:使用

enumerate()

  • 需要同时遍历多个列表:使用

zip()

  • 需要反向遍历:使用

reversed()

  • 需要排序后遍历:使用

sorted()

  • 处理嵌套列表:使用嵌套循环
  • 需要过滤元素:使用

filter() 或带条件的列表推导式

根据具体需求选择最适合的遍历方式。

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4