我目前遇到以下代码问题,请看一下:
def readData(fileName):
inputFile = open(fileName, 'r')
yearList = []
locList = []
line = inputFile.readline()
while line != "":
line = line.strip()
year, loc = line.split("\t")
yearList = yearList + [year]
locList = locList + [loc]
line = inputFile.readline()
inputFile.close()
return yearList, locList
def findLocation(yearList, locList, year):
location = "Not Found"
for i in range(len(locList)):
if locList[i] == year:
location = locList[i]
print(location)
def main():
fileName = input("Please enter the name of the file here:")
yearList, locList = readData(fileName)
print(yearList)
print(locList)
year = int(input("Enter the year you want the function to look for in the data:"))
location = findLocation(yearList, locList, year)
每次运行代码时,它都会执行findLocation函数之前的所有操作,它不会返回值,而是返回" Not Found"。我已经尝试改变循环并尝试索引和类似的东西,但我只是无法弄清楚为什么它会一直返回" Not Found"而不是位置。谁能帮我?
答案 0 :(得分:1)
执行此操作时:
year, loc = line.split("\t")
您将字符串分配给year
,然后将此字符串附加到您的yearList。
但是,你做了
year = int(input("Enter the year you want the function to look for in the data:"))
并为本地变量year
分配一个整数。最终发生的是你将一个整数与一个字符串进行比较,例如你最终会为每个案件"2016"==2016
做False
。
要更正此问题,请删除int()
功能并仅使用字符串。