簡體   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