Python:max(以字符为单位的数字列表)给出对与错的答案 [英] Python: max(a list of numbers as characters) gives right and wrong answer

查看:78
本文介绍了Python:max(以字符为单位的数字列表)给出对与错的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,这是确切的情况-请考虑以下列表:

So here's the exact scenario- consider the list:

x = ['4','5','29','54','4','0','-214','542','-64','1',-3","6",-6"] 现在, max(x)应该给出 '542' ,而不是'6',但是如果您取出'6',它的确给出了'542'的最大值.另一方面, min(x)正确地给出了'-214'作为答案.

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.

如果将 x 转换为数字列表,则显然 max(x)会给出正确的输出 542 .至少从我对Python的了解来看,这是一种不可靠的行为,我想探究一下我是否在这里缺少有关 max()函数如何工作的解释该行为的信息.

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.

推荐答案

在编写此问题并尝试通过 max()函数理解此行为时,我尝试了 x.sort(),它给出了答案.因此,让我粘贴排序后的列表:

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"]

所以基本上这些都是字符串,字符串的初始字符决定了它的值为字符串.意思是, 5kaify 6kaify 首先.

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)将给出 'd' 作为答案,因为按字母顺序,它将比列表中的所有字符串晚,因此 max() 会检查字母顺序是否是字符串/字符列表的值,而不是其整数/数值.希望这会有所帮助.

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.

这篇关于Python:max(以字符为单位的数字列表)给出对与错的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆