为了保持一个干净的问题,问题在代码中注释:)
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
答案 0 :(得分:2)
你在比较字符串,而不是数字,所以事情会变得有些奇怪。将您的变量转换为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)
答案 1 :(得分:1)
假设文件中每个非空白行的空格前有一个点:
with open('text.txt') as file:
highest = max(int(line.partition('.')[0]) for line in file if line.strip())