Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用max函数时返回的值不正确_Python_Python 3.x_Max - Fatal编程技术网

Python 使用max函数时返回的值不正确

Python 使用max函数时返回的值不正确,python,python-3.x,max,Python,Python 3.x,Max,以下代码返回不正确的最大值: maximum = 0 f =open("data.dat", "r") for line in f: global maximum fields = line.split() classcode = fields[0] name = fields[1] scr = fields[2] maximum=max(scr) print(classcode, name, scr) f.close() print

以下代码返回不正确的最大值:

maximum = 0
f =open("data.dat", "r")

for line in f:
    global maximum
    fields = line.split()
    classcode = fields[0]
    name = fields[1]
    scr = fields[2]

    maximum=max(scr)
    print(classcode, name, scr)

f.close()
print("maximum=", maximum)
数据文件是

1 test2 100
1 test1 100
1 test3 20
1 test4 60
1 test5 33
我得到的结果是

1 test2 100
1 test1 100
1 test3 20
1 test4 60
1 test5 33
maximum= 3
如果您知道我为什么得到错误的值,我们将不胜感激

您正在对每个值应用
max()
max()
没有可与该值进行比较的内容。事实上,它会在
scr
中找到值最高的一个字符,它只是一个字符串(一个字符序列)。在上一个
scr
值中,字符串
'33'
,两个字符的值相等,因此它选择了一个,
'3'

收集列表中的值(首先转换为整数后),然后在该列表上调用
max()
,这样会更有效。那么它就有了可以比较的东西:

scores = []

for line in f:
    fields = line.split()
    classcode = fields[0]
    name = fields[1]
    scr = int(fields[2])
    scores.append(scr)
    print(classcode, name, scr)

maximum = max(scores)
print("maximum=", maximum)
maximum=max(scr)
的作用与您认为的不同。它比较字符串
scr
中字符的值


我认为您需要的是
max=max(int(scr),max)
。这会选择当前值或旧的最大值中较大的一个,并对整数而不是字符串起作用。

我认为您在循环中缺少了
分数。追加(scr)
行。@Blckknght:facepalmCheers非常有用。