首页 > 解决方案 > Python: What function should I use? min() and max() doesn't seem to work?

问题描述

I have a program that inputs different lists and it seems to work fine with some lists but not with others. Would appreciate if you could explain this to me, thanks.

This input doesn't work:

input_list = ['-9', '-9', '-9', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8']
print(min(input_list))

Output(which obviously doesn't work considering there's a '-9' value in the list):

-8

Now if I change the input_list[0] to '-10' instead this works for some reason:

input_list = ['-10', '-9', '-9', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8.5', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8', '-8']
print(max(input_list))

Output(It works fine):

-10

If I use print(max(input_list)) I instead get Output: -9 in both above examples

min() and max() works fine on positive number-lists, but not on negatives.

Considering the input changes according to different text files(logs) I need to find a way around this.

This just shows how I get the files etc., to give you some insight:

from tkinter import filedialog
def openfile(filename):
    with open(filename, 'r') as inputfile:
        columns = inputfile.readlines()
        column1 = [column.split()[7] for column in columns]
        return column1
filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("txt files","*.txt"),("all files","*.*")))
columnlist = openfile(filename)
c1 = columnlist[1:]
print(min(c1))

标签: python

解决方案


with strings, the built-in function min will return the minimum alphabetical character, for example for -9 and -8 will evaluate the first character which is '-' and '-' since they are equal will evaluate the second characters which are '8' and '9', and character '8' is the minimum so the function will return -8 and makes perfect sense;

if you want to find the minimum float, then you have to give floats to your function, you can use the key param to transform to float your list elements during the comparison:

min(input_list, key=float)

output:

'-9'

same logic apply to the max built-in function


推荐阅读