Skip to main content
 首页 » 编程设计

python之如何将列表元素转换为 int 并将其与数字进行比较

2024年09月07日8dflying

我有一个由空格分隔的 txt 格式的平面文件。

ID  Math    Eng Phy 
A   70      75  77 
B   56      79  80 
C   90      89  56 

如果小于 70,我需要比较每个数字。 我在做什么:我可以将此文件存储在字典中,但是当我比较数字时:

"if int(m) < 70:ValueError: invalid literal for int() with base 10: 'Math' "  

错误。下面是我的代码:

with open('student.txt','r') as file: 
     rows = ( line.split('\t') for line in file ) 
     d = { row[0]:row[1:] for row in rows } 
for l in d: 
    print(l,d[l]) 
    for m in d[l]: 
        if int(m) < 70: 
           print(m) 

请您参考如下方法:

您需要跳过第一行,因为它是标题:

next(rows) 
d = { row[0]:row[1:] for row in rows } 

顺便说一句,rows 是一个 generator所以最好不要为了分配更少的内存而耗尽它:

with open('student.txt','r') as f: 
    rows = ( line.split('\t') for line.strip() in f ) 
    next(rows) 
 
    for l in rows: 
        for m in l[1:]: 
            if int(m) < 70: 
                print(m)