Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我的网站的服务器脚本中有一小段 python 代码,看起来有点像这样:
console.append([str(x) for x in data]) console.append(str(max(data)))
很简单,你可能会想,但是它输出的结果是这样的:
['3', '12', '3'] 3
出于某种原因,python 认为 3 是 [3,12,3] 的最大值!
那我做错了吗?或者这是python的不当行为?
因为'3'ASCII 表中的字符高于'1'. 您正在比较字符串,而不是数字。如果要比较数字,则需要将它们转换为数字。一种方法是max(data, key=int),但您可能希望将数字实际存储在列表中。
'3'
'1'
max(data, key=int)
我对 Python 知之甚少,但您使用的是字符串的最大值,这意味着'3..'大于'1..'.
'3..'
'1..'