与此 for 循环等效的 while 循环是什么?

What is the while loop equivalent to this for loop?

我想将代码中的 for 循环转换为 while 循环。这是代码。

class CountryCatalogue:
    def __init__(self, countryFile):  # constructor method that takes name of file
        self.countryCat = []  # The instance variable country cat needed
        file = open(countryFile, "r")  # open and read the file
        for strip in file:
            strip = strip.strip()
            data = strip.split('|')  # Remove '|' in each line
            clean_data = Country(data[0], data[2], data[3], data[1])  # Create an object to country
            self.countryCat.append(clean_data)  # Append the item to the list
        file.close()  # Close the file

    def setPopulationOfCountry(self, country, population):
        for pop in range(len(self.countryCat)):  # iterate through countryCat
            if self.countryCat[pop].getName() == country.getName():
                self.countryCat[pop].setPopulation(population)  # updating data if needed

我试着用这种方式更改第二个 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)  # updating data if needed
            pop = pop + 1

但它没有用,我不确定第一个 for 循环。

你的 while 循环:

def setPopulationOfCountry(self, country, population):
    pop = 0
    while pop < (len(self.countryCat)):
        if self.countryCat[pop].getName() == country.getName():
            self.countryCat[pop].setPopulation(population)  # updating data if needed
            pop = pop + 1

你把pop = pop + 1放在if语句里,取出来:

def setPopulationOfCountry(self, country, population):
    pop = 0
    while pop < (len(self.countryCat)):
        if self.countryCat[pop].getName() == country.getName():
            self.countryCat[pop].setPopulation(population)  # updating data if needed
        pop = pop + 1

我发现将文件 for 循环更改为 while 循环的最简单方法是遍历每一行:

file = open(countryFile, "r")  # open and read the file
strip = file.readline()
while strip != "":
    strip = file.readline()