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

Python for循环range逆序参数与while stack判断语法疑问

from typing import List  

def dailyTemperatures(temperatures: List[int]) -> List[int]:
    temp_count = len(temperatures)
    ans = [0]*temp_count
    
    stack = []
    idx_stack = []
    
    for idx in range(temp_count-1,-1,-1): // first point
      temperature = temperatures[idx]
      
      last_temp_idx = 0
      while stack: // second point
        last_temp = stack[-1]
        last_temp_idx = idx_stack[-1]
        if last_temp <= temperature:
          stack.pop()
          idx_stack.pop()
        else:
          break
      
      if len(stack) == 0:
        stack.append(temperature)
        idx_stack.append(idx)
        ans[idx] = 0
        continue
        
      stack.append(temperature)
      idx_stack.append(idx)
      ans[idx] = last_temp_idx-idx
    
    return ans

问题1解答

Python内置的range函数传入3个参数时,语法规则为range(起始值, 终止值, 步长),遍历逻辑遵循左闭右开:生成的序列包含起始值,不包含终止值,每次按步长的数值增减。
对应代码里的range(temp_count-1, -1, -1):

  • 第一个参数temp_count-1是遍历起始索引:温度数组的索引范围是0到len(temperatures)-1也就是temp_count-1,这段逻辑要从数组最后一位倒着往前遍历,所以起始值设为它。
  • 第二个参数-1是遍历终止值:因为左闭右开的规则,要让遍历能覆盖到索引0,就得把终止值设为0的前一位也就是-1,这样遍历到0之后下一个值是-1,会触发终止条件,不会继续。
  • 第三个参数-1是步长:代表每次循环索引减1,实现倒序遍历的效果。
    你理解的每次循环索引递减1是对的,两个-1分别对应终止值和步长,作用完全不同。

问题2解答

Python里所有容器类型(列表、字典、元组等)做布尔判断时,空容器会被判定为False,非空容器会被判定为True。
所以while stack:的判断逻辑是:当stack不为空时,执行循环体内的代码,如果stack是空的,会直接跳过整个while循环,和你猜测的逻辑刚好相反。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:15:02