问题
So here's the exact scenario- consider the list:
x=['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6']
now max(x)
should give '542' instead it gives '6', but if you take out '6' it does give '542' as max. min(x)
on the other hand correctly gives '-214' as the answer.
if you convert x into a list of numbers then obviously max(x)
gives the correct output 542. This is an unreliable behavior at least from what I know about Python and I would like to explore if I am missing something here on how max()
function works that could explain this behavior.
回答1:
As I was writing this question and trying to understand this behavior with max()
function, I tried x.sort()
and it gave out the answer. So let me paste the sorted list:
['-214', '-3', '-6', '-64', '0', '1', '29', '4', '4', '5', '54', '542', '6']
So basically these are strings and initial character of the string decides its value as string. Meaning, 5kaify
will come first than 6kaify
.
For more clarity, if I add bunch of alphabets into this list as below:
x=['4', '5', '29', '54', '4', '0',
'd'
, '-214', '542', '-64', '1',
'a'
, '-3',
'c'
, '6', '-6']
max(x)
will give 'd'
as the answer as alphabetically it would come later than all the strings in the list, hence max()
checks for alphabetical order as the value for list of strings/characters and not its integral/numeric value. Hope this was helpful.
回答2:
You are taking string not int. While taking string: they are sorted alphabetically.
x.sort()
:
['-214', '-3', '-6', '-64', '0', '1', '29', '4', '4', '5', '54', '542', '6']
You need to use map to convert them into int.
max(map(int,x))
# 542
回答3:
Here is another approach,
>>> x=['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6']
>>>
>>> max(x, key=lambda x : int(x))
'542'
>>> min(x, key=lambda x : int(x))
'-214'
回答4:
So essentially max and min when using a string will use alphabetically highest character. Think of the array
['all','b','c','d']
max will list d as the answer as when sorting alphabetically we first rely on the initial character and only with duplicates do we check the next character.
So when we try to sort numbers as a string it will use the same logic. Therefore 6 will be higher than 562 since 6 > 5.
Alphabetically the order is symbols < numbers (in order 0-9) < characters (in order a-z)
I hope that answers your question.
来源:https://stackoverflow.com/questions/63185645/python-maxa-list-of-numbers-as-characters-gives-right-and-wrong-answer