繁体   English   中英

为什么 max() 在 python 中产生错误的输出?

[英]Why does max() produce wrong output in python?

numbers=input("Enter numbers separated by space")
x=numbers.split()
mx=max(x)
print(mx)

输入是 4 5 29 54 4 0 -214 542 -64 1 -3 5 6 -6。

输出应该是 542 但我得到的输出是 6!

将它们转换为整数,然后应用函数。

numbers=input("Enter numbers separated by space")
x=[int(i) for i in numbers.split()]
mx=max(x)
print(mx)

输出:

542

输入是字符串。 您需要将其转换为整数。

numbers=input("Enter numbers separated by space")
x=map(int, numbers.split())
mx=max(x)
print(mx)

#542

其他人已经解释了发生了什么,但由于 Python 有一个 repl,我将用它来向您展示 python 认为正在发生的事情。

>>> nums = input('insert space separated numbers ')
insert space separated numbers 1 2 3 4 5
>>> nums
'1 2 3 4 5'
>>> type(nums)
<class 'str'>
>>> nums.split(' ')
['1', '2', '3', '4', '5']
>>> type(nums.split(' '))
<class 'list'>

到这里,一切都说得通了。 我们从用户那里读取一个字符串,当我们拆分它时,我们得到一个列表。

>>> type(nums.split(' ')[0])
<class 'str'>

这应该仍然有意义,但需要解释。 我们将一个字符串拆分为一个字符列表。 为了将其解释为整数,我们需要对其调用int方法。

>>> [int(x) for x in nums.split(' ')]
[1, 2, 3, 4, 5]

把这一切放在一起

>>> max([int(x) for x in nums.split(' ')])
5

为了帮助解释以上内容,

>>> '1' == 1
False
>>> '1' < 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: '<' not supported between instances of 'str' and 'int'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM