我循环浏览文件以找到最高值,然后返回值和行数。如果我没有用myMax
转换int()
,我会得到一个无序类型错误,变量设置为字符串。我忘记了什么?!
def main():
myMax= 0
myCount = 0
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
if int(line) > int(myMax):
myMax = line
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
main()
答案 0 :(得分:3)
您需要将myMax = line
更改为myMax = int(line)
。这也会使if int(line) > int(myMax):
转换为if int(line) > myMax:
答案 1 :(得分:0)
此文件包含有效数字,而不包含无法转换为数字的字符串。
with open('numbers.dat') as f:
lines = [int(line) for line in f if line.strip()]
print 'Out of %s lines, the highest value is %s' % (len(lines),max(lines))
答案 2 :(得分:0)
我想'myMax = line'这一行导致它 - 你进行了类型转换(如果是int(line)> int(myMax):)但是没有分配它。如果:
def main():
myMax = 0
with open("numbers.dat", 'r') as myFile:
for i, line in enumerate((int(x) for x in myFile)):
if line > myMax:
myMax = line
print ("Out of %s lines, the highest value found was %s" % (i, myMax))
main()
如果您有空行并想跳过它们:
def main():
myMax = 0
with open("numbers.dat", 'r') as myFile:
for i, line in enumerate((int(x) for x in myFile if x)):
if line > myMax:
myMax = line
print ("Out of %s lines, the highest value found was %s" % (i, myMax))
main()
答案 3 :(得分:0)
如果您的“numbers.dat”文件在整个文件中包含字符串和数字,那么这就是我用来解决问题的方法。我不得不逐个字符地分解行,然后将多个数字的数字构建到字符串变量myTemp中,然后每当没有字符的数字时,我检查myTemp的大小以及是否有任何内容将它变成一个整数并将其分配给myInt,将myTemp变量重置为空(如果行上有另一个数字,它将不会添加到已存在的数字),然后将其与当前的Max进行比较。这是几个ifs,但我认为它可以做到这一点。
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def main():
myMax= 0
myCount = 0
myTemp = ''
lastCharNum = False
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
for char in line: #go through each character on the line
if is_number(char) == False: #if the character isnt a number
if len(myTemp) == 0: #if the myTemp is empty
lastCharNum = False #set lastchar false
continue #then continue to the next char
else: #else myTemp has something in it
myInt = int(myTemp)#turn into int
myTemp = '' #Flush myTemp variable for next number (so it can check on same line)
if myInt > myMax: #compare
myMax = myInt
else:# otherwise the char is a num and we save it to myTemp
if lastCharNum:
myTemp = myTemp + char
lastCharNum = True #sets it true for the next time around
else:
myTemp = char
lastCharNum = True #sets it true for the next time around
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
main()
如果“numbers.dat”文件每行只有数字,那么这很容易解决:
def main():
myMax= 0
myCount = 0
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
if int(line) > myMax: #compare
myMax = int(line)
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
main()