gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:51 25 4
gpt4 key购买 nike

我有一个由空格分隔的 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)

关于python - 如何将列表元素转换为 int 并将其与数字进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48750897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com