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

Python代码中的for循环如何转换为等效的while循环?

你改写的第二个for循环存在逻辑错误:你把计数器pop的自增语句放在了if判断的内部,只有匹配到对应国家时计数器才会加1,一旦遇到不匹配的国家,计数器就不再更新,程序会直接陷入死循环。

两个while循环的等效正确写法如下:

1. 修正后的setPopulationOfCountry方法(原第二个for循环改写)

def setPopulationOfCountry(self, country, population):
    pop = 0
    while pop < len(self.countryCat):
        if self.countryCat[pop].getName() == country.getName():
            self.countryCat[pop].setPopulation(population)
        # 计数器自增要放在if分支外,每次循环都更新索引
        pop += 1

2. __init__方法中遍历文件的for循环改写

原for strip in file是迭代文件对象逐行读取,转while循环可以用readline()方法逐行读取,判断读到的内容为空时终止循环即可:

def __init__(self, countryFile):
    self.countryCat = []
    file = open(countryFile, "r")
    # 读取第一行作为初始判断条件
    line = file.readline()
    while line:
        strip = line.strip()
        data = strip.split('|')
        clean_data = Country(data[0], data[2], data[3], data[1])
        self.countryCat.append(clean_data)
        # 读取下一行,更新循环判断条件
        line = file.readline()
    file.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:15:04