我是python新手,作业有问题。我想从一个位置读取一个文件,并查找一个数字在该文件中出现的次数。我已经完成了你看文件和拿到名单的地方。我还在程序中使用线性搜索来查找数字。然而,无论我做什么,我都会得到答案的数字是不在名单上。有人能帮我吗? 这是我的代码:
import os.path
fLocation="C://TEMP//"
print("Assumed file location is at: ", fLocation)
fName = input("\nPlease enter a file name with its extension (ex. XXX.txt): ")
try:
fin = open(fLocation + fName, 'r')
aStr = fin.read()
aList = aStr.split()
def linearSearch(intList,target):
found=False
position=0
while position<len(intList):
if intList[position] == target:
found=True
break
position=position+1
return found
mynum=int(input("What is the number you are looking for in the file?"))
filenum= linearSearch(aList, mynum)
if filenum:
print("The number is in index: ",aList)
else:
print("The number is not in the list")
您得到的答案是错误的,因为您正在比较}
string
和{您的}。您在接受输入时正在将{}解析为int。删除int解析,字符串将匹配。在
intList
是string
的列表,而不是{另外,如果您期望
print("The number is in index: ",aList)
将打印与字符串匹配的索引,那么您将无法获得正确的输出,因为它显示的是输入列表,而不是包含索引的列表。在相关问题 更多 >
编程相关推荐