最小和最大函数返回不正确的值 [英] Min and max functions returns incorrect values

查看:73
本文介绍了最小和最大函数返回不正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 2.7在文本文件中查找最高和最低值.

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

文本文件的格式很简单,每一行都带有一个Integer值. 以下代码从文件中收集数字:

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))

我从印刷品中得到的是: 最大值:8974 最小值:11239

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.

我认为我对python的理解可能存在根本性的错误,请帮助我确定我的误解.

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

推荐答案

从文件中读取后,列表中将充满字符串.您需要将它们转换为整数/浮点数,否则max/min不会返回max/min 数字值.下面的代码将使用列表将data_list中的每个值转换为整数理解,然后返回最大值.

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])

您可以在事实之前执行此操作,因此不必为min再次进行转换:

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)

注意:如果您使用浮点数,则应在列表理解中使用float而不是int.

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

顺便说一句,这对于字符串不起作用的原因是max将从字符串的开头开始比较字符串的序数值.在这种情况下,"8"大于"1".

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'.

这篇关于最小和最大函数返回不正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆