Min and max functions returns incorrect values [duplicate]

*爱你&永不变心* 提交于 2019-12-10 21:30:16

问题


I am using python 2.7 to find highest and lowest values in an text file.

The text file is simply formatted with one Integer value at each line. The following code collects the numbers from the file:

with open(data_file, 'r') as f:
    data_list = f.readlines()

Then I try to reach for the maximum and minimum values with:

max_value =  max(data_list)
min_value = min(data_list)
print('Max value: '+ str(max_value) + ' Min value: ' + str(min_value))

What I then get from the print is: Max value: 8974 Min value: 11239

How can the max value be smaller than the minimum? I have also tried printing the whole list and there are both higher and lower values than what stated above. In the text file there are also higher and lower values than stated above.

I feel that there might be something fundamentally wrong in my understanding of python, please help me pinpoint my misconception.


回答1:


As you've read from a file your list will be full of strings. You need to convert these to ints/floats otherwise max/min will not return the max/min numerical values. The code below will convert each value in data_list to an integer using a list comprehension and then return the maximum value.

max_value = max([int(i) for i in data_list])

You could do this before the fact so you don't have to convert it again for min:

with open(data_file, 'r') as f:
    data_list = [int(i) for i in f.readlines()]

max_value =  max(data_list)
min_value = min(data_list)

Note: if you have floats then you should use float instead of int in the list comprehension.

Incidentally, the reason this doesn't work for strings is that max will compare the ordinal values of the strings, starting from the beginning of the string. In this case '8' is greater than '1'.



来源:https://stackoverflow.com/questions/26761734/min-and-max-functions-returns-incorrect-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!