【发布时间】:2015-02-22 10:19:59
【问题描述】:
目前我正在将一组变量保存到一个文本文件中。我正在执行以下操作以检查我的代码是否有效,但是每当我使用两位数(例如 10)时,它都不会将此数字打印为最大数字。
如果我的文本文件看起来像这样。
tom:5
tom:10
tom:1
它会输出 5 作为最大数字。
name = input('name')
score = 4
if name == 'tom':
fo= open('tom.txt','a')
fo.write('Tom: ')
fo.write(str(score ))
fo.write("\n")
fo.close()
if name == 'wood':
fo= open('wood.txt','a')
fo.write('Wood: ')
fo.write(str(score ))
fo.write("\n")
fo.close()
tomL2 = []
woodL2 = []
fo = open('tom.txt','r')
tomL = fo.readlines()
tomLi = tomL2 + tomL
fo.close
tomLL=max(tomLi)
print(tomLL)
fo = open('wood.txt','r')
woodL = fo.readlines()
woodLi = woodL2 + woodL
fo.close
woodLL=max(woodLi)
print(woodLL)
【问题讨论】:
-
您在比较字符串,而不是数字。在使用
max之前,您需要将它们转换为floats。 -
好吧,像这样:keys.sort(key=float)
-
没那么简单。就 Python 而言,字符串只是一个无定形的字符序列:它不知道里面是否有人类可读的数字。为了提取该数字,您需要明确地parse 字符串。
-
非常感谢您辛苦了
标签: list file python-3.x max