[英]Creating lists from a text file by splitting it vertically
我想使用 Python 將此文本文件分成 3 個(稱為x
、 y
和e
)列表,但我似乎做不到。
這是文本文件(稱為數據)的樣子:
x y e
-2 2.1 0.170358869161
0 2.4 0.170202773308
2 2.5 -0.138557648063
4 3.5 0.187965696415
6 4.2 -0.473073365465
這是我目前無法使用的代碼:
x=[]
y=[]
e=[]
try:
data = open('data.txt', 'rt')
except:
sys.exit('cannot find file')
with data:
try:
x.append(data[:1])
y.append(data[2:3])
e.append(data[4:5])
except:
sys.exit('cannot create lists')
做這個:
with data as f: # f is the file object
for line in f: # you can iterate over a file object line-by-line
xi, yi, ei = line.split()
x.append(xi)
y.append(yi)
e.append(ei.strip()) # ei will have a \n on the end
如果你對它們的形狀的假設是正確的,你可以在追加它們時將它們強制為int或浮動。
如果你有熊貓,我推薦read_csv
:
>>> import pandas as pd
>>> pd.read_csv('data.txt', delim_whitespace=True)
x y e
0 -2 2.1 0.170359
1 0 2.4 0.170203
2 2 2.5 -0.138558
3 4 3.5 0.187966
4 6 4.2 -0.473073
你可以使用csv lib:
import csv
x, y, e = [], [], []
with open("in.csv") as f:
next(f)
for a, b, c in csv.reader(f, delimiter=" ", skipinitialspace=1):
x.append(float(a))
y.append(float(b))
e.append(float(c))
輸出:
[-2.0, 0.0, 2.0, 4.0, 6.0]
[2.1, 2.4, 2.5, 3.5, 4.2]
[0.170358869161, 0.170202773308, -0.138557648063, 0.187965696415, -0.473073365465]
或者使用defaultdict對元素進行分組:
import csv
from collections import defaultdict
with open("in.csv") as f:
d = defaultdict(list)
for dct in csv.DictReader(f, delimiter=" ", skipinitialspace=1):
for k, v in dct.items():
d[k].append(float(v))
from pprint import pprint as pp
pp(dict(d))
輸出:
{'e': [0.170358869161,
0.170202773308,
-0.138557648063,
0.187965696415,
-0.473073365465],
'x': [-2.0, 0.0, 2.0, 4.0, 6.0],
'y': [2.1, 2.4, 2.5, 3.5, 4.2]}
我看到上面的回復有使用硬編碼變量的答案。 但是我找到了一種方法來創建可以容納無限行的列表。
def getFrom(index: int, data: list):
returnList = []
for item in data:
if len(item) >= index:
returnList.append(item[index])
else:
returnList.append("")
return returnList
在這個function中,data是你要查找的列表,可以嵌套,index是你要查找的索引。 這將返回一個列表,其中包含垂直空間索引中的內容。
你也可以試試
data = ...
endList = [getFrom(index, data) for index in range(len(data))]
和 endList 如果數組垂直拆分的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.