我的函数不能像预期的那样工作。当所有行[0]小于行[2]时,我总是得到'真'。我知道这是很琐碎,但它是一个练习,我已经采取了更好地了解文件和for循环中的比较运算符
def contains_greater_than(filename):
"""
(str) --> bool
The text file of which <filename> is the name contains multiple lines.
Each line consists of two integer numbers, separated by a space.
This returns True iff in at least one of those lines, the first number
is larger than the second one.
"""
lines = open(filename).readlines()
for line in lines:
if line[0] > line[2]:
return True
return False
我的数据:
3 6
3 7
3 8
2 9
3 20
你的代码读取'返回True如果任何线路,线[0]>行[2]'。这是真的,因为'3> 2'。只读取第一个和第三个字符,意思是'3 20''读取'line [0] = 3 line [2] = 2' – njzk2