def ints(filename):
a = []
f = open(filename, "r")
lines = f.readlines()
f.close()
for line in lines:
numbers = line.split()
for number in numbers:
a.append(int(number))
return a
到目前为止,这是我的函数,我希望能够读取包含整数和字符(如“x”和“b”等)的文件并返回仅包含整数的列表。目前该函数只能处理包含整数的文件。
如何修改它以排除字符或字母?
请您参考如下方法:
这是我对您的代码所做的编辑,它的表现符合您的预期。
def ints(filename):
"""A function that takes the filename of a file as an input arguement, computs and returns a list of
integers of all the numbers in the file."""
a = []
f = open(filename, "r")
lines = f.readlines()
f.close()
for line in lines:
for character in line:
try:
a.append(int(character))
except ValueError:
pass
return a
