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

前端 未结 1 1849
盖世英雄少女心
盖世英雄少女心 2021-01-25 11:58

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

相关标签:
1条回答
  • 2021-01-25 12:10

    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.

    0 讨论(0)
提交回复
热议问题