python知识点二:列表遍历


下面介绍 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值