Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我的max和min程序适用于某些值,但也不适用于某些值_Python_Python 3.x_List - Fatal编程技术网

Python 我的max和min程序适用于某些值,但也不适用于某些值

Python 我的max和min程序适用于某些值,但也不适用于某些值,python,python-3.x,list,Python,Python 3.x,List,重写程序,该程序提示用户输入 编号并打印出以下位置的最大值和最小值: 用户输入“完成”时结束。编写程序来存储 用户在列表中输入的数字,并使用max()和min()函数 循环完成后计算最大值和最小值 lst=[] while True: data=input('Enter the Input : ') if data == 'done': break else: lst.append(data) print(ls

重写程序,该程序提示用户输入 编号并打印出以下位置的最大值和最小值: 用户输入“完成”时结束。编写程序来存储 用户在列表中输入的数字,并使用max()和min()函数 循环完成后计算最大值和最小值

lst=[]
while True:
    
    data=input('Enter the Input : ')
    if data == 'done':
        break
    else:
        lst.append(data)
        

print(lst)
print('The maximum number of list is ',max(lst))
print('The minimum number of list is ',min(lst))
用相同的代码给我错误的答案:

Enter the Input : done
['12', '212', '32']
The maximum number of list is  32
The minimum number of list is  12

您的
lst
是一个字符串数组。因此
min
max
使用字典排序,当然,例如,
“10”
小于
“3”
。在将输入值添加到列表之前,请将其转换为数值

lst.append(int(data))

因此,您将得到一个数字列表,然后
min
max
将按预期工作。

问题是您在字符串列表上使用max()/min(),您希望成为整数(或浮点)列表

您只需要转换用户添加的每一位数据,并可以写一个检查,以确保这是一个数字,如果需要

lst=[]
while True:
    
    data=input('Enter the Input : ')
    if data == 'done':
        break
    try: 
        lst.append(int(data))
    except ValueError:
        print('Input must be a number! Please try again.')
        

print(lst)
print('The maximum number of list is ',max(lst))
print('The minimum number of list is ',min(lst))

max(lst,key=int)
您能解释一下为什么要将数字存储为字符串吗。您不需要列表,只需使用两个变量
min\u number
max\u number
在每次输入后更新它们
key
是一个可调用项,它将获取列表元素并返回一个用作排序键的对象。在这种情况下,例如
int('212')
将返回
212
。您需要比较整数值,因为对字符串进行词汇排序会给出错误的顺序。[编辑:更正,我们不是在这里排序-我们是在获取最大值。但这是同一个问题,因为在这两种情况下,它取决于值之间的比较,以及哪个值应被视为较高值。]或者,将整数放在列表的第一位:
lst.append(int(data))
lst=[]
while True:
    
    data=input('Enter the Input : ')
    if data == 'done':
        break
    try: 
        lst.append(int(data))
    except ValueError:
        print('Input must be a number! Please try again.')
        

print(lst)
print('The maximum number of list is ',max(lst))
print('The minimum number of list is ',min(lst))