[英]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.