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非常有用。