开发者

Crazy python behaviour

开发者 https://www.devze.com 2022-12-08 08:38 出处:网络
I have a little piece of python code in the server script for my website which looks a little bit like this:

I have a little piece of python code in the server script for my website which looks a little bit like this:

console.append([str(x) for x in data])
console.append(str(max(data)))

quite simple, you might think, however the result it's outputting is this:

['3', '12', '3']
3

for some reason python thinks 3 is the max of [3,12,3]!

So am I d开发者_如何学Pythonoing something wrong? Or this is misbehaviour on the part of python?


Because the character '3' is higher in the ASCII table than '1'. You are comparing strings, not numbers. If you want to compare the numerically, you need to convert them to numbers. One way is max(data, key=int), but you might want to actually store numbers in the list.


I know very little Python, but you are taking the max of strings, which means that '3..' is greater than '1..'.

0

精彩评论

暂无评论...
验证码 换一张
取 消