Why can't I find max number in a file like thi

2019-03-01 09:38发布

问题:

I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the list. I tried to do so with the following code:

i = 0
with open('jan14.nSets.txt','r') as data:
    for num in data:
        if num > i:
            i = num
print(i)

where jan14.nSets.txt is the following:

12
80
46
51
0
64
37
9
270
23
132
133
16
6
18
23
32
75
2
9
6
74
44
41
56
17
9
4
8
5
3
27
1
3
42
23
58
118
100
185
85
63
220
38
163
27
198

Rather than 270, I receive 9 as an output, and I do not understand why this is the case. I know that there are builtins for this, but I would like to know why this doesn't work to help me understand the language. I am using python2.7

回答1:

num is a string, not a number. Turn it into an integer first using int():

num = int(num)

You are comparing text, so it is ordered lexicographically, '9' > '80' because the ASCII character '9' has a higher codepoint than '8':

>>> '9' > '80'
True

After the '9' line, all other lines either have an initial digit that is smaller than '9', or the line is equal.

You could use the max() function instead, provided you first use map() to turn all lines into integers:

with open('jan14.nSets.txt','r') as data:
    i = max(map(int, data))

or use a generator expression (in Python 2, more memory efficient than map()):

with open('jan14.nSets.txt','r') as data:
    i = max(int(num) for num in data)

Both pull in all lines from data, map the lines to integers, and determine the maximum value from those.