[英]Python - read numbers from text file and put into list
因此,就像標題中所說的,我開始學習一些python,而我在使用這項技術時遇到了麻煩。 我需要完成的工作是讀一些數字並將它們存儲在列表中。 文本文件如下所示:
0 0 3 50
50 100 4 20
基本上,這些是用於python的海龜制作形狀的坐標和方向。 我要講的是,唯一的問題是使它們采用正確的格式。 所以我不知道如何將這些數字從文件中獲取到[ [0, 0, 3, 50], [50, 100, 4, 20] ]
列表中,每個四個坐標是一個列表一個大清單。
這是我的嘗試,但正如我所說,我需要一些幫助-謝謝。
polyShape=[]
infile = open(name,"r")
num = int(infile.readline(2))
while num != "":
polyShape.append(num)
num = int(infile.readline(2))
infile.close()
with open('data.txt') as f:
polyShape = []
for line in f:
line = line.split() # to deal with blank
if line: # lines (ie skip them)
line = [int(i) for i in line]
polyShape.append(line)
會給你
[[0, 0, 3, 50], [50, 100, 4, 20]]
這將適用於包含(或不包含)空行的文件。
完成操作或遇到異常時,使用with
構造將自動為您關閉文件。
假設您的輸入文件中實際上沒有空行:
with open(name, "r") as infile:
polyShape = [map(int, line.split()) for line in infile]
說明: map(int, line.split())
分割每一line
並將每一部分轉換為一個int
。 [X for Y in Z]
構造是一個列表推導,它依次將映射map
到文件的所有行上,並將其結果返回到列表中。
如果您現在覺得這太復雜了,則map(int, line.split())
是主要的帶回家的消息。
with open('data.txt') as f:
lis=[map(int,x.split()) for x in f if x.strip()] # if x.strip() to skip blank lines
#use list(map(int,x.split())) in case of python 3.x
這就是map()
工作方式:
>>> map(int,'1 2 3 4'.split())
[1, 2, 3, 4]
遍歷文件是最簡單的方法:
poly_shape = []
with open(name, 'r') as handle:
for line in handle:
if not line.strip():
continue # This skips blank lines
values = map(int, line.split())
poly_shape.append(values)
單線:
[ [int(x) for x in line.split(' ')] for line in open(name,'r').readlines() if line.strip()]
但readlines
部分可能不是一個好主意。
我非常確定[int(x) for x in ... ]
比其他建議的解決方案中使用map
更快。
編輯
感謝Blender:不需要.readlines
,這很酷,所以我們只有:
[ map(int, line.split()) for line in open(name,'r') if line.strip()]
我還使用了map(int, )
因為它實際上更快,並且您也可以只使用line.split()
代替line.split(' ')
。
我不建議對大數組使用append
。 這比創建零數組和為其賦值要慢50倍。
import numpy
fname = "D:\Test.txt";
num_lines = sum(1 for line in open(fname));
array = numpy.zeros((num_lines,4));
k = 0;
with open(fname, "r") as ins:
for line in ins:
a =[int(i) for i in line.split(' ')];;
array[k,0:4] =a;
k = k+1;
print(array)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.