1

为了保持一个干净的问题,问题在代码中被注释了:)

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
4

2 回答 2

2

你在比较字符串,而不是数字,所以事情可能会有点奇怪。将您的变量转换为 afloat或 anint它应该可以工作

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-26T01:31:04.337 回答
1

假设文件中每个非空白行的空格前都有一个点:

with open('text.txt') as file:
  highest = max(int(line.partition('.')[0]) for line in file if line.strip())
于 2012-12-26T04:32:28.397 回答