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
相关产品推荐
相关产品推荐

