目录
下面介绍 Python 遍历列表的全部方式及示例代码:
1. 使用 for 循环遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
输出结果:
apple
banana
cherry
2. 使用 while 循环遍历列表
fruits = ['apple', 'banana', 'cherry']
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
输出结果:
apple
banana
cherry
3. 使用列表推导式遍历列表
fruits = ['apple', 'banana', 'cherry']
[print(fruit) for fruit in fruits]
输出结果:
apple
banana
cherry
4. 使用 map() 函数遍历列表
fruits = ['apple', 'banana', 'cherry']
list(map(print, fruits))
输出结果:
apple
banana
cherry
5. 使用 filter() 函数过滤列表元素并遍历
numbers = [1, 2, 3, 4, 5]
[print(num) for num in filter(lambda x: x % 2 == 0, numbers)]
输出结果:
2
4
6. 使用 zip() 函数遍历多个列表
fruits = ['apple', 'banana', 'cherry']
prices = [1.2, 2.3, 3.4]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ${price}")
输出结果:
apple: $1.2
banana: $2.3
cherry: $3.4
7. 使用 reversed() 函数反向遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in reversed(fruits):
print(fruit)
输出结果:
cherry
banana
apple