我想將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回圈。
uj5u.com熱心網友回復:
你的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
uj5u.com熱心網友回復:
我發現將檔案 for 回圈更改為 while 回圈的最簡單方法是遍歷每一行:
file = open(countryFile, "r") # open and read the file
strip = file.readline()
while strip != "":
strip = file.readline()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374903.html
