python - 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))
解决方案
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
推荐阅读
- postgresql - 如何回顾以前的同类型记录
- python-3.x - 如何根据数据框值和字典键向数据框添加行
- c++ - pugixml 包含设置为未从 pugixml 配置 cmake 文件中找到的目录
- java - 代理背后的 UnknownHostException
- macros - 如何用宏获取类方法的参数类型?
- ios - 如何在表格视图上显示信息
- java - 如何在 Android 中以编程方式在 Spinner 上设置重叠锚点?
- reactjs - 如何从 SharePoint 列表项中获取数组中的总数
- python - 在 groupby 之后切片组并在子图中绘图
- python - 挂钩烧瓶的文件更改检测的方法?