为了保持问题清晰,问题被注释在代码中:)
theOpenFile = open('text.txt', 'r')
highest = 0
for myCurrentString in theOpenFile.readlines():
## Simple string manipulation
stringArray = myCurrentString.split() ## to get value, this seems to
series = stringArray[0].split('.')[0] ## work perfectly when I
## "print series" at the end
if series > highest: ## This doesn't work properly,
highest = series ## although no syntantic or
print "Highest = " + series ## runtimes errors, just wrong output
print series
theOpenFile.close()输出
Highest = 8
8
Highest = 6
6
Highest = 6
6
Highest = 8
8
Highest = 8
8
Highest = 7
7
Highest = 4
4发布于 2012-12-26 09:31:04
您比较的是字符串,而不是数字,所以事情可能会变得有点奇怪。将您的变量转换为float或int,它应该可以工作
with open('text.txt', 'r') as theOpenFile:
highest = 0
for myCurrentString in theOpenFile:
stringArray = myCurrentString.split()
try:
series = float(stringArray[0].split('.')[0])
except ValueError:
# The input wasn't a number, so we just skip it and go on
# to the next one
continue
if series > highest:
highest = series
print "Highest = " + series
print series一种更简洁的方法是这样:
with open('text.txt', 'r') as handle:
numbers = []
for line in handle:
field = line.split()[0]
try:
numbers.append(float(field)) # Or `int()`
except ValueError:
print field, "isn't a number"
continue
highest = max(numbers)发布于 2012-12-26 12:32:28
假设文件中每个非空行的空格前都有一个点:
with open('text.txt') as file:
highest = max(int(line.partition('.')[0]) for line in file if line.strip())https://stackoverflow.com/questions/14035176
复制相似问题