Python: max(a list of numbers as characters) gives right and wrong answer [duplicate]

故事扮演 提交于 2020-08-10 01:12:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!