Crazy python behaviour
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..'
.
精彩评论