【发布时间】:2022-01-12 00:26:30
【问题描述】:
我想将我代码中的两个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 循环。
【问题讨论】:
-
但是为什么?另外,为什么
countryCat不是以国家/地区名称为键的字典,以便您可以按名称查找它们没有循环? -
因为我向我的朋友展示了我的代码并且我害怕他会复制它,所以我想将我所有的 for 循环更改为 while 循环。 CountryCat 不是 dict 键控,因为用户之前输入了文件并且程序不知道将输入哪个文件,它只是创建一个空列表,然后用文件数据填充它。
标签: python loops for-loop while-loop