Skip to main content
 首页 » 编程设计

python之for循环中的比较运算符

2025年05月04日15oomusou

我的功能无法正常工作。当所有行 [0] 都小于行 [2] 时,我一直得到“真”。我知道这很微不足道,但这是我为了更好地理解文件而进行的练习

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 

请您参考如下方法:

在我之前深思熟虑的回答中得到了彻底的教育,我可以提供这个更简单的解决方案,它仍然按预期短路:

for line in lines: 
    x, y = line.split() 
    if int(x) > int(y): return True 
return False