You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环疑问:为何无需range(len())也能遍历列表?

问题与解答

项目代码

# Three different lists

hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

prices = [30, 25, 40, 20, 20, 35, 50, 35]

last_week = [2, 3, 5, 8, 4, 4, 6, 2]


new_prices = [price - 5 for price in prices]
print(str(new_prices)) #prints 25, 20, 35, 15, 15, 30, 45, 30

total_revenue = 0

for i in range(len(hairstyles)):
  total_revenue += prices[i] * last_week[i]

print("Total Revenue: " + str(total_revenue))


cuts_under_30 = [hairstyles[i] for i in range(len(hairstyles)) if new_prices[i] < 30]
print(str(cuts_under_30))

疑问

项目运行正确且已通过,但我有个疑问:为何在new_prices的列表推导式中无需使用range(len(new_prices))就能遍历列表?遍历列表是否必须使用range(len())?希望了解原理用于后续学习。

解答

Python里遍历列表有两种核心逻辑,对应不同的使用场景:

  • 直接遍历元素(即for price in prices的写法):
    列表在Python中属于「可迭代对象」,当你用for 元素 in 列表的格式时,Python会自动调用列表的迭代器,逐个取出内部元素,完全不需要手动处理索引。这种写法简洁直观,只要你只需要元素本身、不需要用到它在列表中的位置时,这是最优选择——就像你生成new_prices时,只需要对每个价格做减5操作,根本不需要关心它的索引,直接遍历元素就足够。

  • 通过索引遍历(用range(len())的方式):
    这种方式是先获取列表长度,生成一个连续的索引范围(比如range(len(hairstyles))会生成0到7的整数),再通过索引i去访问对应位置的元素(比如prices[i])。它的适用场景是必须用到索引本身的时候:比如计算total_revenue时,需要同时取prices和last_week两个列表对应位置的元素相乘,索引i就是关联两个列表的关键;或者需要修改原列表特定位置的元素时,也必须依赖索引。

总结:遍历列表完全不需要必须用range(len()),相反,只要场景允许,直接遍历元素是更符合Python风格的写法。如果确实需要同时拿到索引和元素,还可以用更优雅的enumerate()函数,比如for i, price in enumerate(prices),能一次性获取索引和对应的元素,比range(len())更清晰。

内容的提问来源于stack exchange,提问作者DSyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:13:18