[英]Python: reading integers in a file and adding them to a list
我正在尝试创建一个函数,该函数将打开的文件作为参数,读取文件中所有位于其自己行上的整数,然后创建这些整数的列表。 空行时,该函数应停止读取文件。 这就是我所坚持的。
def load_ints(file):
lst = []
x = 1
while x == 1:
for line in file:
if len(line.strip()) != 0:
load = line.split()
load = [int(i) for i in load]
lst = lst + load
else:
x = 2
x = 2
return lst
我正在测试的文件如下所示:
1
0
-12
53
1078
Should not be read by load_ints!
len(line.strip()) != 0:
无法正常工作,它目前给我一个ValueError:int()的无效文字,基数为10:“应该”
您需要在x = 2
之后稍作break
else:
x = 2
break
否则, for
循环将继续遍历文件。 它已读取空白行,执行else
条件,然后继续处理行。 因此它尝试处理“应该...”行,但由于“应该...”不是整数而失败。
另外,我不明白为什么要使用while
语句。 for
循环应足以遍历文件并处理每一行,而当空行出现时,我建议的break
将退出循环。
其他答案已经指出了这个问题:在对空行进行包围运算时,必须停止解析整数。
这是使用itertools.takewhile
的单行代码,在剥离行时停止会产生空行并转换为整数:
import itertools
def load_ints(file):
return [int(x) for x in itertools.takewhile(str.strip,file)]
结果:
[1, 0, -12, 53, 1078]
因此itertools.takewhile
在file
行上进行迭代,并在每一行上应用strip
。 如果结果为空字符串,则停止迭代。 否则它将继续,因此该行将转换为整数并添加到列表推导中。
在这种情况下,您写的行越少,使用辅助变量和状态创建的错误就越少。
当您读取文件时,您将获得一个生成器。 与其将所有内容读取到内存中,我们不如使用while循环一次向我们喂入1行,并在满足条件时中断(行为空白)。 这应该是最有效的解决方案。
data = """\
1
2
-10
1241
Empty line above"""
with open("test.txt","w") as f:
f.write(data)
with open("test.txt") as f:
data = []
while True:
row = next(f).strip()
try:
data.append(int(row))
# Break if ValueError is raised (for instance blank line or string)
except ValueError:
break
data
返回值:
[1, 2, -10, 1241]
如果您想要一个紧凑的解决方案,我们可以使用itertools中的takewhile。 但这不会处理任何错误。
from itertools import takewhile
with open("test.txt") as f:
data = list(map(int,takewhile(lambda x: x.strip(), f)))
我认为这是没有必要的。
def load_ints(file):
lst = []
for line in file:
if len(line.strip()) != 0:
load = line.split()
load = [int(i) for i in load]
lst.append(load)
else:
break
return lst
如果您想在行为空时停止读取文件,则必须中断for
循环:
def load_ints(file):
lst = []
for line in file:
if len(line.strip()) != 0:
load = line.split()
load = [int(i) for i in load]
lst = lst + load
else:
break
return lst
您还可以使用re
模块:
import re
def load_ints(my_file):
return list(map(int, re.findall('-?\d', my_file.read())))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.