Skip to content Skip to sidebar Skip to footer

Min And Max Functions Returns Incorrect Values

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 num

Solution 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/minnumerical 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:

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

Post a Comment for "Min And Max Functions Returns Incorrect Values"