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

如何将Python中print_stacks函数的for循环改写为while循环?

替换for循环为while循环的实现

这里把你代码里的两个for循环分别转换成while循环,逻辑完全一致:

def print_stacks(n, stacks):
    # 替换第一个for循环:从n-1递减到0
    i = n - 1
    while i >= 0:
        # 替换第二个for循环:遍历stacks中的每个元素
        stack_idx = 0
        while stack_idx < len(stacks):
            stack = stacks[stack_idx]
            if i < len(stack):
                print(stack[i], end=" ")
            stack_idx += 1
        i -= 1

替换说明:

  • 外层循环:原来的for i in range(n-1, -1, -1)是从n-1开始,每次减1直到i=0。用while循环时,先初始化i = n-1,循环条件设为i >= 0,每次循环结束后执行i -= 1完成递减。
  • 内层循环:原来的for stack in stacks是遍历列表中的每个元素。用while循环时,通过索引stack_idx来遍历,初始化为0,循环条件是stack_idx < len(stacks),每次循环后stack_idx += 1,同时通过stacks[stack_idx]获取当前栈元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:11:18